22

Is there an isDate function in jQuery?

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

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Kuttan Sujith
  • 7,889
  • 18
  • 64
  • 95
  • chk this out : http://docs.jquery.com/Plugins/Validation/Methods/date http://stackoverflow.com/questions/511439/custom-date-format-with-jquery-validation-plugin – jknair Oct 07 '10 at 10:18

11 Answers11

39

If you don't want to deal with external libraries, a simple javascript-only solution is:

function isDate(val) {
    var d = new Date(val);
    return !isNaN(d.valueOf());
}

UPDATE:     !!Major Caveat!!
@BarryPicker raises a good point in the comments. JavaScript silently converts February 29 to March 1 for all non-leap years. This behavior appears to be limited strictly to days through 31 (e.g., March 32 is not converted to April 1, but June 31 is converted to July 1). Depending on your situation, this may be a limitation you can accept, but you should be aware of it:

>>> new Date('2/29/2014')
Sat Mar 01 2014 00:00:00 GMT-0500 (Eastern Standard Time)
>>> new Date('3/32/2014')
Invalid Date
>>> new Date('2/29/2015')
Sun Mar 01 2015 00:00:00 GMT-0500 (Eastern Standard Time)
>>> isDate('2/29/2014')
true  // <-- no it's not true! 2/29/2014 is not a valid date!
>>> isDate('6/31/2015')
true  // <-- not true again! Apparently, the crux of the problem is that it
      //     allows the day count to reach "31" regardless of the month..
mwolfe02
  • 23,787
  • 9
  • 91
  • 161
  • for asp.net if you use a CustomValidator control you can call a function from ClientValidationFunction property, this function should be more or less: function IsDate(sender, args) { var d = new Date($('#tbBirthDate').val()); args.IsValid = !isNaN(d.valueOf()); return; } – juanytuweb Sep 17 '14 at 12:41
  • 1
    This method does not work correctly for 2/29/2014 - there was no leap year for 2014. In fact, this method says 2/30/2014 is valid - and this will never be valid. When using 2/30/2014 as input, the variable 'd' is assigned the value of March 2, 2014 on the first line in your function, so some implicit conversion is occurring... – barrypicker Nov 21 '14 at 20:30
  • @barrypicker: Thanks for the heads-up. I updated my answer accordingly. – mwolfe02 Nov 21 '14 at 20:44
  • 1
    This method also fails for a hex color string containing no letters, e.g. "#000000". – radicalbiscuit Dec 27 '14 at 10:10
  • plz stay out of this answer as it really does not work at all and u will get kicked off of your team. You shuold use moment js eg: moment('2012-05-25', 'YYYY-MM-DD', true).isValid(); – alecellis1985 Nov 27 '18 at 12:18
6

simplest way in javascript is:

function isDate(dateVal) {
  var d = new Date(dateVal);
  return d.toString() === 'Invalid Date'? false: true;
}
isambitd
  • 829
  • 8
  • 14
5

Depending on how you're trying to implement this, you may be able to use the "validate" jQuery plugin with the date option set.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
irishbuzz
  • 2,420
  • 1
  • 19
  • 16
4

There's no built-in date functionality in jQuery core...and it doesn't really do anything directly to help with dates, so there aren't many libraries on top of it (unless they're date pickers, etc). There are several JavaScript date libraries available though, to make working with them just a bit easier.

I can't answer for sure what's best...it depends how they're entering it and what culture you're dealing with, keep in mind that different cultures are used to seeing their dates in different format, as a quick example, MM/DD/YYYY vs YYYY/MM/DD (or dozens of others).

Community
  • 1
  • 1
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
1

The problem is that entering in February 31st will return a valid date in JavaScript. Enter in the year, month, and day, turn it into a date, and see if that date matches what you input, instead of some day in March.

function isDate(y, m, d) {
    var a = new Date(y, m-1, d); 
    // subtract 1 from the month since .getMonth() is zero-indexed.
    if (a.getFullYear() == y && a.getMonth() == m-1 && a.getDate() == d) { 
        return true; 
    } else {
        return false;
    } 
}

Technically, this is vanilla JavaScript, since jQuery doesn't really expand on the native Date object.

invot
  • 533
  • 7
  • 30
1

Date.parse will prb sort you out, without the need for jquery:

http://www.w3schools.com/jsref/jsref_parse.asp

Above removed after some kind soul pointed out how basic parseDate really is.

There is also a $.datepicker.parseDate( format, value, options ) utility function in the JQuery UI Datepicker plugin:

https://api.jqueryui.com/datepicker/

Rhys Jones
  • 5,348
  • 1
  • 23
  • 44
Matt Roberts
  • 26,371
  • 31
  • 103
  • 180
1

The best way to get user date input is a date picker that only provides valid dates. It can be done with a string, but you are liable to rile your users by demanding they use your chosen format.

You need to specify in your validator if dates precede months.

This uses a second argument to enforce the order. With no second argument it uses the computer's default order.

// computer default date format order:
Date.ddmm= (function(){
    return Date.parse('2/6/2009')> Date.parse('6/2/2009');
})()

allow month names as well as digits: '21 Jan, 2000' or 'October 21,1975'

function validay(str, order){
    if(order== undefined) order= Date.ddmm? 0: 1;
    var day, month, D= Date.parse(str);
    if(D){
        str= str.split(/\W+/);

        // check for a month name first:
        if(/\D/.test(str[0])) day= str[1];
        else if (/\D/.test(str[1])) day= str[0];
        else{
            day= str[order];
            month= order? 0: 1;
            month= parseInt(str[month], 10) || 13;
        }
        try{
            D= new Date(D);
            if(D.getDate()== parseInt(day, 10)){
                if(!month || D.getMonth()== month-1) return D;
            }
        }
        catch(er){}
    }
    return false;
}
kennebec
  • 102,654
  • 32
  • 106
  • 127
1

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
}
Mike Cheel
  • 12,626
  • 10
  • 72
  • 101
0

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.)

  • Doesn't work in ie! (ie converts it into a completely different valid date!) I was going to convert a C function I wrote for embedded software which verifies the day according to the month but I thought I only had to do such low level stuff in my day job! They have a datepicker, I'll verify it server side with VB isdate. Job done. – user2981217 Nov 12 '13 at 23:45
0

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

Vikash Mishra
  • 349
  • 3
  • 18
0

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();
alecellis1985
  • 131
  • 2
  • 15