1

I am trying to verify a date input with a try catch in java script, but the following code doesn't work as I expect it. I expect that the error when the entered date is not date, the catch should execute but here is what I get. see no new date and nothing displayed of what i expect.

console.log("min date :")
    try{
         minDate = new Date(elminDate.value)
    }
    catch(e){
        console.log("error::")
        console.log(err.name)
        console.log("changed min")
         minDate = new Date()
    }
    console.log(minDate)

    console.log("max date :" )
    try{
         maxDate = new Date(elmaxDate.value)
    }
    catch(err){
        console.log("error::")
        console.log(err.name)
        console.log("changed max")
        maxDate = new Date()
    }
    console.log(maxDate)

response :

[Log] min date : (home.html, line 93)
[Log] Tue Aug 01 2017 02:00:00 GMT+0200 (CEST) (home.html, line 103)
[Log] max date : (home.html, line 105)
[Log] Invalid Date (home.html, line 115)
gxmad
  • 1,650
  • 4
  • 23
  • 29
  • 2
    Are you sure the date constructor throws? When i use it with invalid data i just get a `Date` that shows `invalid Date` when converted to string. Also see [this post](https://stackoverflow.com/questions/1353684/detecting-an-invalid-date-date-instance-in-javascript) – ASDFGerte Aug 08 '17 at 15:03
  • Yes, I am getting Invalid Date, so it is just a string? I am waiting an error but as you say that does not throw it. – gxmad Aug 08 '17 at 15:11
  • See [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_date), only some methods on the invalid Date **may** throw, the constructor doesn't from what i've read. That means it is a `Date` object which is invalid, no exceptions will be thrown. Again, see [this post](https://stackoverflow.com/questions/1353684/detecting-an-invalid-date-date-instance-in-javascript) for detecting invalid dates. – ASDFGerte Aug 08 '17 at 15:13
  • That's perfect, thanks for the help, I am just working with the tostring method, compare it to invalid date if so change the date. that's all i search, thanks – gxmad Aug 08 '17 at 15:34

1 Answers1

2

The Date constructor doesn't throw exceptions on invalid dates, but rather produces a NaN value in the Date object. You can test for that:

console.log("date :");
date = new Date(elDate.value);
if (isNaN(date)) {
    console.log("error: Invalid Date");
    console.log("changed date to now");
    date = new Date();
}
console.log(date)
Bergi
  • 630,263
  • 148
  • 957
  • 1,375