1

I'm using JavaScipt's new Date(datestring) to parse user input on IE11.

The specific line of code is

var date = new Date(enteredText);

It accepts any parameter for day field - for example, 5/50/1997 parses to June 19, 1997, because June 19 would be the 50th day of May.

Is there a way to force it to not do this and to only accept real dates?

Aric TenEyck
  • 8,002
  • 1
  • 34
  • 48
  • You could check the value before you create the date object. But I tried it in chrome and I couldn´t create a date with a day greater 30/31. It returned "Invalid Date" – David P. Nov 10 '15 at 14:46
  • You'll need to parse the date yourself. If you pass an invalid date string to the date constructor, [browsers are free to interpret as they please](http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.4.2): _"If the String does not conform to that format the function may fall back to any implementation-specific heuristics or implementation-specific date formats."_ – James Thorpe Nov 10 '15 at 14:50
  • Different browsers treat the date function differently. Some returns a date some return invalid date. – CAllen Nov 10 '15 at 14:50
  • 1
    The `Date` object is fundamentally broken in JavaScript, if you need to work with dates on the frontend I suggest using [momentjs](http://momentjs.com/), the extra bytes will save you a ton of time and headaches – mfeineis Nov 10 '15 at 14:57

2 Answers2

2

You will have to parse the string on your own to verify if the date is valid. To do this you will need to split the string by a delimiter ('/' in this case) and check each day/month/year is valid.

Where you put this validation is entirely up to you. You can override the Date constructor using Date.prototype.constructor = function(){/*your code here*/} or you can create a custom function that validates the string before instantiating a new date function validateDate(str){/*your code here*/}. The latter is probably your best bet.

Divide100
  • 224
  • 1
  • 2
  • 11
  • Hmmph. Seems a bit unreasonable to write a date parsing routine before calling the built-in date parsing routine. Ah, JavaScript... – Aric TenEyck Nov 10 '15 at 15:02
0

You can split the parameter passed by '/' or depending on your delimiter is and manually check if the date, month and year is valid before passing it to the date function

CAllen
  • 856
  • 5
  • 14