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?
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.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With