Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Date Validation in JavaScript

Validate dates in JavaScript: catch Invalid Date with isNaN, check YYYY-MM-DD format, ranges, past and future, and reject 30 February. Explanation and output.

BeginnerJavaScript Date and Time ProgramsExample 9 of 10

The sample output was captured with the clock set to 15 January 2024, 10:30:45 UTC. Your run will show your own date, time and time zone.

date-validation.js
1// Method 1: Check if valid date
2function isValidDate(date) {
3 return date instanceof Date && !isNaN(date.getTime());
4}
5
6console.log('Valid:', isValidDate(new Date()));
7console.log('Invalid:', isValidDate(new Date('invalid')));
8
9// Method 2: Validate date string
10function isValidDateString(dateString) {
11 const date = new Date(dateString);
12 return isValidDate(date) && dateString !== 'Invalid Date';
13}
14
15console.log('Valid string:', isValidDateString('2024-01-15'));
16console.log('Invalid string:', isValidDateString('not-a-date'));
17
18// Method 3: Validate date format
19function isValidDateFormat(dateString, format = 'YYYY-MM-DD') {
20 const patterns = {
21 'YYYY-MM-DD': /^\d{4}-\d{2}-\d{2}$/,
22 'DD/MM/YYYY': /^\d{2}\/\d{2}\/\d{4}$/,
23 'MM/DD/YYYY': /^\d{2}\/\d{2}\/\d{4}$/
24 };
25
26 if (!patterns[format].test(dateString)) {
27 return false;
28 }
29
30 const date = new Date(dateString);
31 return isValidDate(date);
32}
33
34console.log('Valid format:', isValidDateFormat('2024-01-15', 'YYYY-MM-DD'));
35
36// Method 4: Validate date range
37function isDateInRange(date, minDate, maxDate) {
38 if (!isValidDate(date)) return false;
39 return date >= minDate && date <= maxDate;
40}
41
42const checkDate = new Date('2024-01-15');
43const min = new Date('2024-01-01');
44const max = new Date('2024-12-31');
45console.log('In range:', isDateInRange(checkDate, min, max));
46
47// Method 5: Validate future date
48function isFutureDate(date) {
49 if (!isValidDate(date)) return false;
50 return date > new Date();
51}
52
53const oneDay = 24 * 60 * 60 * 1000;
54console.log('Future date:', isFutureDate(new Date(Date.now() + oneDay))); // tomorrow
55
56// Method 6: Validate past date
57function isPastDate(date) {
58 if (!isValidDate(date)) return false;
59 return date < new Date();
60}
61
62console.log('Past date:', isPastDate(new Date(Date.now() - oneDay))); // yesterday
63
64// Method 7: Validate date components
65function validateDateComponents(year, month, day) {
66 if (year < 1900 || year > 2100) return false;
67 if (month < 1 || month > 12) return false;
68 if (day < 1 || day > 31) return false;
69
70 const date = new Date(year, month - 1, day);
71 return date.getFullYear() === year &&
72 date.getMonth() === month - 1 &&
73 date.getDate() === day;
74}
75
76console.log('Valid components:', validateDateComponents(2024, 1, 15));
77console.log('Invalid components:', validateDateComponents(2024, 2, 30)); // Feb 30 doesn't exist

Sample Output

Valid: true
Invalid: false
Valid string: true
Invalid string: false
Valid format: true
In range: true
Future date: true
Past date: true
Valid components: true
Invalid components: false

In this one

  • How to detect an Invalid Date
  • How to check a format with a regular expression
  • How to validate ranges, past and future
  • How to catch dates that roll over, like 30 February

How it works

  1. 1

    isValidDate accepts a real date and rejects new Date("invalid").

  2. 2

    isValidDateString checks two strings.

  3. 3

    isValidDateFormat checks YYYY-MM-DD.

  4. 4

    isDateInRange checks a date in 2024.

  5. 5

    isFutureDate and isPastDate test tomorrow and yesterday.

  6. 6

    validateDateComponents accepts 15 January and rejects 30 February.

Edge cases

DD/MM/YYYY strings

new Date('15/01/2024') is Invalid Date in many engines.

Split the string and use new Date(year, month - 1, day).

Rollover dates

new Date(2023, 1, 29) becomes 1 March 2023.

Compare the parts after building the date.

Fixed years in checks

isFutureDate(new Date("2025-01-01")) is false after 2025.

Use dates relative to Date.now() in tests.

What's going on

Users type dates in many ways, and some are not dates at all. Date validation makes sure a value is a real, correct date before you save it. It protects forms, keeps data clean, and prevents errors later.

Method 1 checks a Date object. new Date('invalid') does not throw an error. It creates an "Invalid Date" whose getTime() is NaN. NaN means Not a Number. So the test is date instanceof Date && !isNaN(date.getTime()).

Method 2 validates a string by parsing it and running the same check. The extra comparison with 'Invalid Date' is harmless but not needed.

Method 3 checks the format with a regular expression. A regular expression is a pattern for text. /^\d{4}-\d{2}-\d{2}$/ means exactly four digits, a dash, two digits, a dash, two digits, and nothing else. This catches typing mistakes before parsing. One caution: new Date('15/01/2024') does not understand DD/MM/YYYY. It may be invalid or read as a US date. For those formats, split the string and build the date from parts.

Method 4 checks a range, such as dates within this academic year. Methods 5 and 6 check future and past dates. The tests use dates a day before and after now. The first version used fixed years, which gave the wrong answer once those years passed.

Method 7 validates parts: year, month (1 to 12) and day (1 to 31). Then it builds the date and checks that JavaScript did not roll it over. new Date(2024, 1, 30) silently becomes 1 March. Comparing the parts back catches that, so 30 February is rejected. This also handles leap years: 29 February 2024 passes and 29 February 2023 fails.

Best practices: validate early, give clear error messages, handle edge cases and test with tricky dates.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What does new Date("hello").getTime() return?

Pick an answer to check it.

Question 2

validateDateComponents(2024, 2, 29) returns?

Pick an answer to check it.

Questions people ask

Why does new Date("abc") not throw?

JavaScript returns a special Invalid Date object instead of throwing.

Is regex enough?

No. 2024-02-30 matches the pattern but is not a real date.

Why limit years to 1900–2100?

It is a simple sanity range. Adjust it for your app.