Date validation is not common for input fields since dates are ‘picked’ from a date picker rather than typed in. But it has its uses - for e.g. if you are enabling dates in a list view with copy/paste ability, or validating dates sent by a third party system. Let us look at a couple of ways in which you can validate dates.
The Quick and Easy Way
Use a Date
object to create date from a given string. The statement will output either a valid date, or a string “Invalid date.”.
1
2
3
4
5
|
console.log(new Date("2018-12-09"));
// 2018-08-09T00:00:00.000Z
console.log(new Date("29/12/2018")); // Invalid Date
console.log(new Date("32-08-2018")); // Invalid Date
|
More Efficient (?)
You could forego creating a date object for validation by doing a parse.
1
2
3
4
5
6
7
8
9
10
|
console.log(Date.parse("12/09/2018")); // 1544293800000
// 2018-12-08T18:30:00.000Z - local timezone considered
console.log(Date.parse("12/32/2018")); // NaN
// 2018-12-08T18:30:00.000Z - local timezone considered
console.log(Date.parse("12/09/2018 GMT+12:00")); // 1544270400000
console.log("Date long", Date.parse("December 09, 2018 18:00:00 GMT+12:00"));
// 1544335200000, more eleborate way
|
Even More Efficient
Don’t depend on libraries or create objects. Rather, check the input using primitives.
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
|
console.log(isValidDate(2016, 02, 29)); // valid
console.log(isValidDate(2015, 02, 29)); // invalid
console.log(isValidDate(2000, 02, 29)); // valid
console.log(isValidDate(1900, 02, 29)); // invalid
console.log(isValidDate(2018, 01, 32)); // invalid
console.log(isValidDate(2018, 06, 31)); // invalid
function isValidDate(year, month, day) {
switch (true) {
case year < 0:
return "invalid";
case month < 0 && month > 12:
return "invalid";
case month == 1 ||
month == 3 ||
month == 5 ||
month == 7 ||
month == 8 ||
month == 10 ||
month == 12:
if (day > 0 && day <= 31) return "valid";
case month == 4 || month == 6 || month == 9 || month == 11:
if (day > 0 && day <= 30) return "valid";
case month == 2:
if (
((year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) &&
(day > 0 && day <= 29)) ||
(day > 0 && day <= 28)
)
return "valid";
default:
return "invalid";
}
}
|
Do keep in mind that the above logic may not take care of all the edge cases for dates.