How to test a string is valid date or not using moment?

How to test a string is valid date or not using moment?

I would like to test if a date and or time entered is valid.
Can this be done with moment as date and time testing with javascript seems a nightmare. (have spent hours on this).
Test data looks like this.
Invalid
invalid = “”
invalid = ” ”
invalid = “x”
invalid = “1/1”
invalid = “30/2/2015”
invalid = “2/30/2015”

Is Valid
isvalid = “1/12/2015”
isvalid = “1/12/2015 1:00 PM”;

Have tried various javascript methods with hours of trials failing.
I thought moment would have something for this. So tried the following, all of which does not work because I do no think moment works like this.
var valid = moment(input).isDate()
var valid = moment().isDate(input)

My time format is “dd/mm/yyyy”

Solutions/Answers:

Solution 1:

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

Solution 2:

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

Solution 3:

You can use it.

if (startDate == null || !startDate.isValid()) {return false;}

Solution 4:

You can use the Date.parse() function.

Here is the details of how to use.

References