How To Validate Date In Javascript

Validating a date is a common task when it comes to form validation or handling user input. In this blog post, we’ll discuss how to validate a date using JavaScript.

Validating date using the Date object

JavaScript provides a built-in Date object that can be used to create and manipulate dates. When a new Date object is created with an invalid date, it returns an Invalid Date object. We can use this feature to validate a date.

Here’s a function to validate a date:

function isValidDate(dateString) {
    const date = new Date(dateString);
    return !isNaN(date);
}

Let’s test the function with some example inputs:

console.log(isValidDate("2021-07-27")); // true
console.log(isValidDate("2021-02-29")); // false
console.log(isValidDate("2021-13-27")); // false
console.log(isValidDate("not a date")); // false

Validating date using regular expressions

Another way to validate a date is by using regular expressions. This allows us to check if the input string matches a specific format.

Here’s a function to validate a date in the format YYYY-MM-DD:

function isValidDateRegex(dateString) {
    const regex = /^(19|20)\d\d[-](0[1-9]|1[012])[-](0[1-9]|[12][0-9]|3[01])$/;
    return regex.test(dateString);
}

Let’s test the function with some example inputs:

console.log(isValidDateRegex("2021-07-27")); // true
console.log(isValidDateRegex("2021-02-29")); // true
console.log(isValidDateRegex("2021-13-27")); // false
console.log(isValidDateRegex("not a date")); // false

Note that the regex validation method does not account for leap years, so it would consider “2021-02-29” as a valid date. If you need to account for leap years and other date-related rules, it’s recommended to use the Date object method.

Conclusion

In this blog post, we discussed two different methods to validate a date in JavaScript: using the Date object and using regular expressions. Both methods have their pros and cons, so choose the one that best fits your needs.