Sometimes, we want to fix date validation not validating February 31 with JavaScript.
In this article, we’ll look at how to fix date validation not validating February 31 with JavaScript.
How to fix date validation not validating February 31 with JavaScript?
To fix date validation not validating February 31 with JavaScript, we can use some date methods.
For instance, we write:
const isValidDate = (year, month, day) => {
const d = new Date(year, month, day);
return d.getFullYear() === year && d.getMonth() === month && d.getDate() === day
}
console.log(isValidDate(2022, 1, 1))
console.log(isValidDate(2022, 1, 31))
to define the isValidDate
function that checks the year
, month
, and day
of a date.
In it, we create a new Date
instance with them.
Then we get the year, month, and day values from d
to see if they’re the same as the ones from the arguments.
If they’re the same, then we return true
.
Otherwise, we return false
.
Therefore, the first console log logs true
since it’s a valid date and the 2nd log logs false
since it’s not.
Conclusion
To fix date validation not validating February 31 with JavaScript, we can use some date methods.