JavaScript Coder

JavaScript Form Validation - Date

javascript form validation date validation html form validation

It may be tempting to validate date input using regular expressions. However, the better alternative will be to actually convert the date to a date object and test it.

For example, a simple regular expression test would approve this date: 2011/02/29 perfectly valid but there is no such date (since 2011 was not a leap year)

Validate dates in the format: MM/DD/YYYY (or MM-DD-YYYY or MM.DD.YYYY )

function validateDate_MMDDYYYY(input_date) 
{
    var parts = input_date.split(/[\/\-\.]/);

    if (parts.length < 3) 
    {
        return false;
    }

    var dt = new Date(parts[2], parts[0] - 1, parts[1]);
    console.log("date is ", dt.toString());
    
    return (dt && dt.getMonth() === parseInt(parts[0], 10) - 1)

}

This function also allows / - or . (dot) as a seperator These are some valid dates

  • 12/22/2011
  • 2/12/2000
  • 1.1.12
  • 01-01-2013

1.1.12 translates to Jan 1st, 1912. You may want to add year validations to the function.

For example:

if(dt.getFullYear() < 1900)
{
    return false;
}

Try the Demo

Here are the other date format validations:

Validate dates in the format DD/MM/YYYY

function validateDate_DDMMYYYY(input_date) {
    var parts = input_date.split(/[\/\-\.]/);

    if (parts.length < 3) {
        return false;
    }
    var dt = new Date(parts[2], parts[1] - 1, parts[0]);
    console.log("date is ", dt.toString());
    return (dt && dt.getMonth() === parseInt(parts[1], 10) - 1)

}

Try the Demo

Validate dates in the format YYYY/MM/DD

function validateDate_DDMMYYYY(input_date) {
    var parts = input_date.split(/[\/\-\.]/);

    if (parts.length < 3) {
        return false;
    }
    var dt = new Date(parts[0], parts[1] - 1, parts[2]);
    console.log("date is ", dt.toString());
    return (dt && dt.getMonth() === parseInt(parts[1], 10) - 1)

}

Try the demo

See Also