JavaScript: validate a birth date

In JavaScript is quite simple to validate a birth date.

The following code validates a birth date where the minimum age is 18 years and the maximum age is 80 using the YYYY-MM-DD format.


'use strict';

const validateBirthday = (birthday) => {
    if(!/^\d{4}-\d{2}-\d{2}$/.test(birthday)) {
        return -1;
    }
    let parts = birthday.split('-');
    let now = new Date();
    let year = parseInt(parts[0], 10);
    let currentYear = now.getFullYear();
    let month = ( parts[1][0] === '0') ? parseInt(parts[1][1], 10) : parseInt(parts[1], 10);
    let day = ( parts[2][0] === '0') ? parseInt(parts[2][1], 10) : parseInt(parts[2], 10);

    if(year >= currentYear) {
        return -1;
    }
    if( (currentYear - year) < 18 || (currentYear - year) > 80) {
        return -1;
    }
    if( month < 1 || month > 12) {
        return -1;
    }
    if( day < 1 || day > 31 ) {
        return -1;
    }
    return 0;
};

First, we validate the given format against a regular expression pattern. Then we validate date parts: the given year must not be greater than the current year, the difference between the supplied year and the current year must be in a range between 18 and 80, the provided month must be between 1 and 12 and the day must be between 1 and 31.

Prev Articles Next