0

I was trying to check if a date(in MM/dd/yyyy format) is a valid date in javascript. But while passing a wrong date, it is not able to distinguish. I was using the below logic to check if it is a valid date or not.

var dt = document.forms["registerForm"]["dateOfBirth"].value;
    try{
        var d = new Date(dt);
        alert(d);
    }catch(err){
        alert("not a valid date");
        return false;
    }

while the dateOfBirth is "02/47/2016" it is not going to the exception block, rather it is interpreting "02/47/2016" as Fri Mar 18 2016 00:00:00 GMT+0530 (IST). But when i tried with "02/03/2016" it is interpreting correctly as Wed Feb 03 2016 00:00:00 GMT+0530 (IST).

Arindam
  • 185
  • 2
  • 14
  • Possible duplicate of [Detecting an "invalid date" Date instance in JavaScript](http://stackoverflow.com/questions/1353684/detecting-an-invalid-date-date-instance-in-javascript) – casraf Sep 11 '16 at 16:31

2 Answers2

1

Enforce some structure when users enter the date in the form, e.g. MM/DD/YYYY. If you don't you may end up with a date such as 02/10/2016 which could validly be Feb 10th or Oct 2nd depending on the country.

Past that, unless you have to be lean, use moment.js for validation, e.g.

alert(moment("02/10/2016", 'MM/DD/YYYY',true).isValid()); //true
mdubez
  • 3,024
  • 1
  • 17
  • 10
1

The Date constructor gets the day value and just adds that number of days, minus 1, to the first of the month, which explains the resulting date you get.

Using a library like momentjs makes life much easier when it comes to dealing with dates, but if you want to do this without additional library, then you could use the function below. If the Date constructor returns a date object, this function will format that date back to a string, comparing it with the original input. If they don't match, the function will return undefined, just like when an exception occurs. If they match, the date object is returned:

function getDate(d) {
    function formatDate(d) {
        return [d.getMonth() + 1, d.getDate(), d.getFullYear()]
               .map( n => (n < 10 ? '0' : '') + n ).join('/');
    }
    try {
        var d = new Date(dt);
        if (formatDate(d) != dt) return; // invalid
        return d;
    } 
    catch(err){}
}

var dt = '02/47/2016';
console.log(dt, getDate(dt) !== undefined);
var dt = '02/03/2016';
console.log(dt, getDate(dt) !== undefined);
trincot
  • 317,000
  • 35
  • 244
  • 286