Validating a ISO 8601 date using moment.js
Not sure why Praveen's example works in jsfiddle, but the reason your sample doesn't work is because the format isn't YYYY-MM-DD. It includes the time as well, so it's considered invalid. If you try it without the time in the date, it returns true.
Try this instead:moment("2011-10-10T14:48:00", "YYYY-MM-DDTHH:mm:ss", true).isValid()
Okay, I found it.
As per the documentation,
As of version 2.3.0, you may specify a
boolean
for the last argument to make Moment use strict parsing. Strict parsing requires that the format and input match exactly
because you use strict operation, it returns false
. To overcome that use below code:
alert(moment("2011-10-10T14:48:00", "YYYY-MM-DDTHH:mm:ss", true).isValid())
//This will return true
demo1
If you remove the strict parsing
,
alert(moment("2011-10-10T14:48:00", "YYYY-MM-DD").isValid())
//This will return true
demo2
To avoid using string pattern as a second argument, you can just call:
moment("2011-10-10T14:48:00", moment.ISO_8601).isValid() // true
moment("2016-10-13T08:35:47.510Z", moment.ISO_8601).isValid() // true