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
MomentJS handles date validation in an easy way. You need not write lots of code to validate date. 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.
toISOString converts to a Date object, sets to UTC then uses the native Date prototype function to output ISO8601 in UTC with milliseconds ( YYYY-MM-DD[T]HH:mm:ss. SSS[Z] ).
To validate a ISO 8601 date using moment. js, we can use the isValid method. We call moment with the date string to parse and moment. ISO_8601 to parse the date string as an ISO 8601 date string.
ISO 8601 represents date and time by starting with the year, followed by the month, the day, the hour, the minutes, seconds and milliseconds. For example, 2020-07-10 15:00:00.000, represents the 10th of July 2020 at 3 p.m. (in local time as there is no time zone offset specified—more on that below).
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
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
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())
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