0

I'm trying to prevent Javascript from automatically adjusting an invalid date.

For example: 2/31/2000 becomes 3/2/2000

var x = new Date("02/31/2000");
var maxDate = new Date("03/01/2020");

if(x > maxDate){
    //date is invalid
} else {
    //date is valid
}
//March 2st, 2020 is logged to the console
console.log(x); 

What I need: is a solution (in Javascript or Jquery) that does not allow an invalid date like that, instead of auto adjust the month as seen above.

Solution exists here!

Stackoverflow just notified me that there's an answer to this already.

javascript date validation not validation February 31

Not sure what to do with this question... close it? Delete it? Can some mods take the appropriate action please? And thanks!

KidBilly
  • 3,408
  • 1
  • 26
  • 40
  • You'll have to parse the date strings yourself, because that's a basic (and useful) feature of the JavaScript Date facility. – Pointy Oct 01 '20 at 16:44
  • Or of course you could format the resulting date similarly to the input format and compare for equality. In other words, if you make a Date from a source string, then format it to another string, and they're not the same, then the "adjustment" must have occurred. – Pointy Oct 01 '20 at 16:46
  • @Pointy—it's not a specified feature. Parsing of unsupported string formats is implementation dependent. For `new Date("02/31/2000")`, some may return an invalid date (or not…). :-) – RobG Oct 01 '20 at 23:46
  • @RobG well yes that's true of course. My point was that if the runtime is willing to parse the date, it'll also "fix" it (in all cases I know of). I guess egregious bogus dates might get rejected sometimes, like 3-digit month numbers or something. – Pointy Oct 01 '20 at 23:52
  • @Pointy—given `new Date('2020-02-31')`, Safari and Firefox return an invalid date, Chrome returns 2 Mar 2020. :-( – RobG Oct 02 '20 at 02:45

0 Answers0