Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validation of Bad date in Javascript [duplicate]

I'm following this example to validate date string.

While this below example evaluates to true.

var date = new Date('12/21/2019');
console.log(date instanceof Date && !isNaN(date.valueOf()));

This below example also evaluates to true even though it's a bad date.By bad date I mean, that date does not exist in calendar.

var date = new Date('02/31/2019');
console.log(date instanceof Date && !isNaN(date.valueOf()));

Is there a better way of doing it?

like image 388
TheFallenOne Avatar asked Mar 14 '19 17:03

TheFallenOne


People also ask

How do you check if a date is valid or not using moment?

isValid() is the method available on moment which tells if the date is valid or not. MomentJS also provides many parsing flags which can be used to check for date validation.

How do you check if the date is in YYYY MM DD format in JS?

The toISOString() method returns a string formatted as YYYY-MM-DDTHH:mm:ss. sssZ . If the ISO representation of the Date object starts with the provided string, we can conclude that the date string is valid and formatted as YYYY-MM-DD .


1 Answers

using momentjs

moment("02/30/2019", "MM/DD/YYYY", true).isValid(); // false
moment("03/30/2019", "MM/DD/YYYY", true).isValid(); // true

from current docs of the library here: isValid momentjs

moment("not a real date").isValid(); // false

You can still write your own solution by splitting the string and evaluating for each section. the problem with this approach is that not only February that is not 31 days, there are other months too that are only 30 days. so it will take time before you develop a "not buggy" solution.

like image 139
Ramy M. Mousa Avatar answered Sep 17 '22 13:09

Ramy M. Mousa