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.
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.
1// Method 1: Check if valid date2function isValidDate(date) {3 return date instanceof Date && !isNaN(date.getTime());4}56console.log('Valid:', isValidDate(new Date()));7console.log('Invalid:', isValidDate(new Date('invalid')));89// Method 2: Validate date string10function isValidDateString(dateString) {11 const date = new Date(dateString);12 return isValidDate(date) && dateString !== 'Invalid Date';13}1415console.log('Valid string:', isValidDateString('2024-01-15'));16console.log('Invalid string:', isValidDateString('not-a-date'));1718// Method 3: Validate date format19function 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 };2526 if (!patterns[format].test(dateString)) {27 return false;28 }2930 const date = new Date(dateString);31 return isValidDate(date);32}3334console.log('Valid format:', isValidDateFormat('2024-01-15', 'YYYY-MM-DD'));3536// Method 4: Validate date range37function isDateInRange(date, minDate, maxDate) {38 if (!isValidDate(date)) return false;39 return date >= minDate && date <= maxDate;40}4142const 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));4647// Method 5: Validate future date48function isFutureDate(date) {49 if (!isValidDate(date)) return false;50 return date > new Date();51}5253const oneDay = 24 * 60 * 60 * 1000;54console.log('Future date:', isFutureDate(new Date(Date.now() + oneDay))); // tomorrow5556// Method 6: Validate past date57function isPastDate(date) {58 if (!isValidDate(date)) return false;59 return date < new Date();60}6162console.log('Past date:', isPastDate(new Date(Date.now() - oneDay))); // yesterday6364// Method 7: Validate date components65function 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;6970 const date = new Date(year, month - 1, day);71 return date.getFullYear() === year &&72 date.getMonth() === month - 1 &&73 date.getDate() === day;74}7576console.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
isValidDate accepts a real date and rejects new Date("invalid").
- 2
isValidDateString checks two strings.
- 3
isValidDateFormat checks YYYY-MM-DD.
- 4
isDateInRange checks a date in 2024.
- 5
isFutureDate and isPastDate test tomorrow and yesterday.
- 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.