0

I'm trying to check if a date is valid. If I pass 31/02/2018 to new Date it will return Tue Mar 03 1987 00:00:00 GMT+0000 (GMT) as 31/02/2018 is not a real date. So how can I compare the passed date with the return date of new Date? or am I going about this the wrong way altogether.

function isDateValid() {
    var dob = "31/02/1994",
        isValidDate = false;

    var reqs = dob.split("/"),
        day = reqs[0],
        month = reqs[1],
        year = reqs[2];

    var birthday = new Date(year + "-" + month + "-" + day);

    if (birthday === "????") {
        isValidDate = true;
    }

    return isValidDate;
}
user3486427
  • 434
  • 9
  • 18
  • 1
    Possible duplicate of [How to validate a date?](https://stackoverflow.com/questions/5812220/how-to-validate-a-date) – Fabio_MO Jun 06 '18 at 14:37
  • Possible duplicate of [Detecting an "invalid date" Date instance in JavaScript](https://stackoverflow.com/questions/1353684/detecting-an-invalid-date-date-instance-in-javascript) – reisdev Jun 06 '18 at 14:39

2 Answers2

2

You can get the last day of each month by doing this;

var lastDay = new Date(month, year, 0).getDate();

In your case;

function isDateValid(date){
    var isValidDate = false;

    var reqs = date.split("/"),
        day = reqs[0],
        month = reqs[1],
        year = reqs[2],
        lastDay = new Date(month, year, 0).getDate();

    if(day > 0 && day <= lastDay)
        isValidDate = true;

    return isValidDate;
}
ssten
  • 1,848
  • 1
  • 16
  • 28
0

This is what you are looking for. I left your code unchanged and stuck to your original request.

function isDateValid() {
    var dob = "31/02/2018",
        isValidDate = false;

    var reqs = dob.split("/"),
        day = reqs[0],
        month = reqs[1],
        year = reqs[2];

    var birthday = new Date(year + "-" + month + "-" + day);
    
    if (+year  === birthday.getFullYear()&&
        +day   === birthday.getDate()    &&
        +month === birthday.getMonth() + 1) {
        isValidDate = true;
    }

    return isValidDate;
}

console.log(isDateValid());
Attersson
  • 4,755
  • 1
  • 15
  • 29