-1

I have a JSON data containing dates (in mm/dd/yyyy format) which I am converting to Date object using the Date constructor like new Date(year, month, day). I want to return the date object only if the date string is valid. For e.g., for the string '12/08/1992', I should get Tue Dec 08 1992 as expected. But if I pass an invalid date like '15/08/1992' by doing new Date(1992, 14, 8) (month is always n-1 for the Date constructor), I get 'Mon Mar 08 1993', which is not as expected.

Is it possible to check somehow that the entered date is invalid? I can't use any libraries for this.

darKnight
  • 5,651
  • 13
  • 47
  • 87

2 Answers2

0

You can always implement your custom date validator. Keep it simple if you don't want to use any libraries.

VHS
  • 9,534
  • 3
  • 19
  • 43
0
0?[1-9] => 0...9
|  => optional
1[012] => 10..12 
[\/] => / (MM/DD/YYYY)
[12][0-9] => 10 ..... 29
3[01] => 30...31
d{4} => any with length 4 (0000...9999)

var regex = /^(0?[1-9]|1[012])[\/](0?[1-9]|[12][0-9]|3[01])[\/]\d{4}$/;

console.log(regex.test(`12/08/1992`));

console.log(regex.test(`15/08/1992`));
Nishant Dixit
  • 5,388
  • 5
  • 17
  • 29