0

Pretty simple question, how do i validate a datetime, so the input is both the correct format, but also a valid date unlike 2015-02-30 ....

2015-06-28 16:06:35 //Valid
  • you could parse it with the Date object, stringify the result, and then compare the original to the result. If you put too high a value into Date, it rolls over, so the result would have to be different from the original. Check out the MDN pages on the Date object. – Gabriel L. Jun 28 '15 at 15:06
  • Have you tried using the Date object i.e. dt = new Date('2015-06-28 16:06:35');. Anything that is invalid will return with an error. –  Jun 28 '15 at 15:13

2 Answers2

1

Try using moment.js. It's quite good at taking an input of something date-like and parsing it into something usable. It also has an isValid method for determining if the lib was able to parse the date input it was given.

http://momentjs.com/docs/#/parsing/is-valid/

var feb30 = moment('2015-02-30');
var jun28 = moment('2015-06-28');

str = "Feb 30: " + feb30.isValid(); // false
str += "\nJun 28: " + jun28.isValid(); // true

alert(str);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment-with-locales.min.js"></script>
jthomas
  • 858
  • 6
  • 19
0

If you do var d = new Date('2015-02-30'), it will roll over and return the date of 2015-03-02. So, if you compare strings of these values they will be unequal.

Thevs
  • 3,189
  • 2
  • 20
  • 32