I'm trying to validate a ISO 8601 date in javascript using moment.js
console.log(moment("2011-10-10T14:48:00", "YYYY-MM-DD", true).isValid())
It returns false. Where am I going wrong ? Is the date type format incorrect ?
version: Moment 2.5.1
I'm trying to validate a ISO 8601 date in javascript using moment.js
console.log(moment("2011-10-10T14:48:00", "YYYY-MM-DD", true).isValid())
It returns false. Where am I going wrong ? Is the date type format incorrect ?
version: Moment 2.5.1
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
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
booleanfor 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
If you remove the strict parsing,
alert(moment("2011-10-10T14:48:00", "YYYY-MM-DD").isValid())
//This will return true
use this to match part of your date
console.log(moment("2011-10-10T14:48:00", "YYYY-MM-DD", false).isValid())
if you want exact format match then
console.log(moment("2011-10-10T14:48:00", "YYYY-MM-DDTHH:mm:ss", true).isValid())