Validate a date string in JavaScript
This post will discuss how to validate a date string in JavaScript.
There are several ways to validate a date in JavaScript, depending on the format and the criteria of the date. A date is valid if it represents a real calendar date, such as February 29, 2016, but not February 29, 2017. Here are some of the functions we can use:
1. Using Moment.js library
The Moment.js is one of the most popular libraries for working with dates in JavaScript. We can use a third-party library like Moment.js that provides a rich set of functions to parse, validate, manipulate, and display dates in various formats and languages. It supports many different formats and locales, and allows us to specify the format of the input string.
To use Moment.js, we need to include it in our HTML file or import it in our JavaScript file. To validate a date using Moment.js, we can use its isValid() function. This function returns true if the date is valid and false otherwise. We can also specify the format and the strictness of the validation. For instance:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// Import Moment.js in our JavaScript file const moment = require("moment"); // Define a function to validate a date function isValidDate(dateString, format, strict) { // Use Moment.js to parse and validate the date return moment(dateString, format, strict).isValid(); } // Test some examples console.log(isValidDate("2016-02-29", "YYYY-MM-DD", true)); // true console.log(isValidDate("2017-02-29", "YYYY-MM-DD", true)); // false console.log(isValidDate("2016-13-01", "YYYY-MM-DD", true)); // false console.log(isValidDate("Hello", "YYYY-MM-DD", true)); // false |
2. Using a custom function
This is a low-level way to validate a date string in JavaScript by matching it against a pattern of characters. The idea is to use a regular expression to check if the input string matches a valid date format, such as yyyy-mm-dd or mm/dd/yyyy. This function requires us to know the exact format of the input string and have a corresponding regular expression for it. If the input string matches the regular expression, the function will use a custom function to check if the date components, such as year, month, and day, are valid within their ranges. It also check for logical errors, such as February 30th or leap years. The following code illustrates this:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
// Define a function to validate a date function isValidDate(dateString) { // Define a regular expression for yyyy-mm-dd format var regex = /^(\d{4})-(\d{2})-(\d{2})$/; // Check if the input string matches the regex var match = regex.exec(dateString); if (match) { // Get the year, month, and day from the match array var year = parseInt(match[1]); var month = parseInt(match[2]); var day = parseInt(match[3]); // Check if the year is valid if (year < 1000 || year > 9999) { return false; } // Check if the month is valid if (month < 1 || month > 12) { return false; } // Check if the day is valid var daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31]; // Adjust for leap years if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) { daysInMonth[1] = 29; } // Check if the day is within the range of the month if (day < 1 || day > daysInMonth[month - 1]) { return false; } // If all checks pass, return true return true; } // If the input string does not match the regex, return false return false; } // Test some examples console.log(isValidDate("2016-02-29")); // true console.log(isValidDate("2017-02-29")); // false console.log(isValidDate("2016-13-01")); // false console.log(isValidDate("Hello")); // false |
3. Using Date.parse() function
The Date.parse() is a built-in function that parses a date string and returns the number of milliseconds since January 1, 1970, UTC, which is the epoch or reference point for JavaScript dates. If the date string is not valid, it returns an invalid date value, which is NaN (Not a Number). However, this function is not very reliable, because it may accept any string with a number in it as a valid date, and it may not recognize some valid formats or out of range dates.
The following code parses the input string using Date.parse() and then check if it is a valid date by passing the result to the isNaN() function, which returns true if the input is NaN, and false otherwise:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// Define a function to validate a date function isValidDate(dateString) { // Parse the input date string var date = Date.parse(dateString); // Check if the date is valid by passing it to isNaN return !isNaN(date); } // function pass on below inputs console.log(isValidDate("2016-02-29")); // true console.log(isValidDate("2016-13-01")); // false console.log(isValidDate("Hello")); // false // function fails on below inputs console.log(isValidDate("2017-02-29")); // true console.log(isValidDate("26/05/2015")); // false console.log(isValidDate("10")); // true |
That’s all about validating a date string in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)