PalesaDev
PalesaDev

Reputation: 67

Validating Year in a date using JavaScript

I want to validate a person's date of birth and I am stuck trying to figure out how to go about checking if the YEAR of birth is valid using the ISO date format like this yyyy-mm-dd. I want to check if the year is valid and then use the last 2 digits of the year. So I want the format to be yy-mm-dd after validating the year.

I have checked the month and the day but I am struggling to figure out how to validate the year before and after 2000. This is my code for checking MONTH and DAY

function checkDateOfBirth(dateString){
    const year = dateString.substring(0, 2);
    const month = dateString.substring(2, 4);
    const day = dateString.substring(4, 6);

if (
        day > 31 ||
        month > 12 ||
        (month == 2 && day > 29) ||
        (month == (4 || 6 || 9 || 11) && day > 30)
    ) {
        return false;
    }
    return true;
}

The input string would be "940912" in the format yy-mm-dd. Any help/suggestions would be great

Upvotes: 0

Views: 626

Answers (1)

tenshi
tenshi

Reputation: 26344

Why don't you just use the built-in Date object? It'll handle most of the edge cases for you (including Feburary, leap years, etc).

We'd need to fix up the input before passing to the Date, though. I'll reuse the 3 lines that get the year, month, and day, except I'll turn them into numbers first with Number(...).

The only special logic we need for now is that if 2000 + year is greater than this year, then it's probably meant to be a year in the 1900s. Joining the corrected year, month, and day with "-", we now have a string of the form yyyy-mm-dd, which we can pass to the Date.

Lastly, we need to check if the date even makes sense, which we can do by checking if the number returned by getTime is NaN. For example, 000230 doesn't make sense since February can't have a 30th day.

function checkDateOfBirth(dateString) {
  const year = Number(dateString.substring(0, 2));
  const month = Number(dateString.substring(2, 4));
  const day = Number(dateString.substring(4, 6));

  const today = new Date();

  const input = [2000 + year > today.getFullYear() ? "19" + year : "20" + year, month, day].join("-");

  const date = new Date(input);

  return !Number.isNaN(date.getTime());
}

// ok
console.log(checkDateOfBirth("060714"));
console.log(checkDateOfBirth("130406"));
console.log(checkDateOfBirth("450406")); // 1945

// bad
console.log(checkDateOfBirth("060741")); // no July 41st

Upvotes: 1

Related Questions