Valamas - AUS Valamas - AUS - 6 months ago 110
Javascript Question

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"

Answer

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