Date validation in JavaScript
Let's now learn how to check the date for
correctness. For example, January 31st
is a valid date, but January 32d is not.
As you know, JavaScript automatically corrects
dates. In our case, this means that January
32 will automatically become February
1st.
Such a JavaScript property can be used to check for the existence of a date. How we will check: let's create an object with a date and see if parts of the date have changed or not. In other words, whether JavaScript has performed the adjustment on our date or not. If fulfilled, then the date passed by us is incorrect, and if not fulfilled, it is correct.
Let's do the above:
let year = 2025;
let month = 0;
let day = 32;
let date = new Date(year, month, day);
if (date.getFullYear() == year && date.getMonth() == month && date.getDate() == day) {
console.log('correct');
} else {
console.log('incorrect');
}
Make the function checkDate that will
perform the above check. Let the function
return true if the date is correct
and false otherwise. An example of
how this function works for January
31 and January 32:
console.log(checkDate(2025, 0, 31)); // shows true
console.log(checkDate(2025, 0, 32)); // shows false