How can I determine whether a given string represents a date?

Viewed 60304

Is there an isDate function in jQuery?

It should return true if the input is a date, and false otherwise.

11 Answers

If you don't want to use the jquery plugin I found the function at:

http://www.codetoad.com/forum/17_10053.asp

Works for me. The others I found don't work so well.

UPDATED:

From the cached version of the page at: http://web.archive.org/web/20120228171226/http://www.codetoad.com/forum/17_10053.asp

// ******************************************************************
// This function accepts a string variable and verifies if it is a
// proper date or not. It validates format matching either
// mm-dd-yyyy or mm/dd/yyyy. Then it checks to make sure the month
// has the proper number of days, based on which month it is.

// The function returns true if a valid date, false if not.
// ******************************************************************

function isDate(dateStr) {

    var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
    var matchArray = dateStr.match(datePat); // is the format ok?

    if (matchArray == null) {
        alert("Please enter date as either mm/dd/yyyy or mm-dd-yyyy.");
        return false;
    }

    month = matchArray[1]; // p@rse date into variables
    day = matchArray[3];
    year = matchArray[5];

    if (month < 1 || month > 12) { // check month range
        alert("Month must be between 1 and 12.");
        return false;
    }

    if (day < 1 || day > 31) {
        alert("Day must be between 1 and 31.");
        return false;
    }

    if ((month == 4 || month == 6 || month == 9 || month == 11) && day == 31) {
        alert("Month " + month + " doesn`t have 31 days!")
        return false;
    }

    if (month == 2) { // check for february 29th
        var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
        if (day > 29 || (day == 29 && !isleap)) {
            alert("February " + year + " doesn`t have " + day + " days!");
            return false;
        }
    }
    return true; // date is valid
}

I arrived at this solution, made more complicated as I use the European format and javascript is clearly american!

function CheckDate()
{
    var D = document.getElementById('FlightDate').value;
    var values = D.split("-")
    var newD = values [1] + "/" + values [0] + "/" + values[2]
    var d = new Date(newD);
    if(d == 'Invalid Date')document.getElementById('FlightDate').value = "";
}

Messy, but does the job. If your users are american and put the day in the middle, (which I'll never understand!), then you can leave out the split and creation of the newD.

It is probable that I can override the default americanism in the JS by setting culture or some such, but my target audience is exclusively European so it was easier to rig it this way. (Oh, this worked in Chrome, haven't tested it on anything else.)

I guess you want something like this. +1 if it works for you.

HTML

 Date : <input type="text" id="txtDate" /> (mm/dd/yyyy)
 <br/><br/><br/>
<input type="button" value="ValidateDate" id="btnSubmit"/>

jQuery

$(function() {
$('#btnSubmit').bind('click', function(){
    var txtVal =  $('#txtDate').val();
    if(isDate(txtVal))
        alert('Valid Date');
    else
        alert('Invalid Date');
});

function isDate(txtDate)
{
var currVal = txtDate;
if(currVal == '')
    return false;

var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/; //Declare Regex
var dtArray = currVal.match(rxDatePattern); // is format OK?

if (dtArray == null) 
    return false;

//Checks for mm/dd/yyyy format.
dtMonth = dtArray[1];
dtDay= dtArray[3];
dtYear = dtArray[5];        

if (dtMonth < 1 || dtMonth > 12) 
    return false;
else if (dtDay < 1 || dtDay> 31) 
    return false;
else if ((dtMonth==4 || dtMonth==6 || dtMonth==9 || dtMonth==11) && dtDay ==31) 
    return false;
else if (dtMonth == 2) 
{
    var isleap = (dtYear % 4 == 0 && (dtYear % 100 != 0 || dtYear % 400 == 0));
    if (dtDay> 29 || (dtDay ==29 && !isleap)) 
            return false;
}
return true;
}

});

CSS

body{
font-family:Tahoma;
font-size : 8pt;
padding-left:10px;
}
input[type="text"]
{
font-family:Tahoma;
font-size : 8pt;
width:150px;
}

DEMO

You should use moment.js it's the best lib to handle all kind of dates. Solution to your problem:

var inputVal = '2012-05-25';
moment(inputVal , 'YYYY-MM-DD', true).isValid();
Related