How to test a string is valid date or not using moment?
Yes, you could use momentjs to parse it and compare it back with the string
function isValidDate(str) {
var d = moment(str,'D/M/YYYY');
if(d == null || !d.isValid()) return false;
return str.indexOf(d.format('D/M/YYYY')) >= 0
|| str.indexOf(d.format('DD/MM/YYYY')) >= 0
|| str.indexOf(d.format('D/M/YY')) >= 0
|| str.indexOf(d.format('DD/MM/YY')) >= 0;
}
Test code
tests = ['',' ','x','1/1','1/12/2015','1/12/2015 1:00 PM']
for(var z in tests) {
var test = tests[z];
console.log('"' + test + '" ' + isValidDate(test));
}
Output
"" false
" " false
"x" false
"1/1" false
"1/12/2015" true
"1/12/2015 1:00 PM" true
Moment has a function called isValid
.
You want to use this function along with the target date format and the strict parsing parameter to true (otherwise your validation might not be consistent) to delegate to the library all the needed checks (like leap years):
var dateFormat = "DD/MM/YYYY";
moment("28/02/2011", dateFormat, true).isValid(); // return true
moment("29/02/2011", dateFormat, true).isValid(); // return false: February 29th of 2011 does not exist, because 2011 is not a leap year