[javascript] How do I validate a date in this format (yyyy-mm-dd) using jquery?

I am attempting to validate a date in this format: (yyyy-mm-dd). I found this solution but it is in the wrong format for what I need, as in: (mm/dd/yyyy).

Here is the link to that solution: http://jsfiddle.net/ravi1989/EywSP/848/

My code is below:

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;
}

What regex pattern can I use for this that will account for invalid dates and leap years?

This question is related to javascript jquery

The answer is


I expanded just slightly on the isValidDate function Thorbin posted above (using a regex). We use a regex to check the format (to prevent us from getting another format which would be valid for Date). After this loose check we then actually run it through the Date constructor and return true or false if it is valid within this format. If it is not a valid date we will get false from this function.

_x000D_
_x000D_
function isValidDate(dateString) {_x000D_
  var regEx = /^\d{4}-\d{2}-\d{2}$/;_x000D_
  if(!dateString.match(regEx)) return false;  // Invalid format_x000D_
  var d = new Date(dateString);_x000D_
  var dNum = d.getTime();_x000D_
  if(!dNum && dNum !== 0) return false; // NaN value, Invalid date_x000D_
  return d.toISOString().slice(0,10) === dateString;_x000D_
}_x000D_
_x000D_
_x000D_
/* Example Uses */_x000D_
console.log(isValidDate("0000-00-00"));  // false_x000D_
console.log(isValidDate("2015-01-40"));  // false_x000D_
console.log(isValidDate("2016-11-25"));  // true_x000D_
console.log(isValidDate("1970-01-01"));  // true = epoch_x000D_
console.log(isValidDate("2016-02-29"));  // true = leap day_x000D_
console.log(isValidDate("2013-02-29"));  // false = not leap day
_x000D_
_x000D_
_x000D_


Just use Date constructor to compare with string input:

_x000D_
_x000D_
function isDate(str) {_x000D_
  return 'string' === typeof str && (dt = new Date(str)) && !isNaN(dt) && str === dt.toISOString().substr(0, 10);_x000D_
}_x000D_
_x000D_
console.log(isDate("2018-08-09"));_x000D_
console.log(isDate("2008-23-03"));_x000D_
console.log(isDate("0000-00-00"));_x000D_
console.log(isDate("2002-02-29"));_x000D_
console.log(isDate("2004-02-29"));
_x000D_
_x000D_
_x000D_

Edited: Responding to one of the comments

Hi, it does not work on IE8 do you have a solution for – Mehdi Jalal

_x000D_
_x000D_
function pad(n) {_x000D_
  return (10 > n ? ('0' + n) : (n));_x000D_
}_x000D_
_x000D_
function isDate(str) {_x000D_
  if ('string' !== typeof str || !/\d{4}\-\d{2}\-\d{2}/.test(str)) {_x000D_
    return false;_x000D_
  }_x000D_
  var dt = new Date(str.replace(/\-/g, '/'));_x000D_
  return dt && !isNaN(dt) && 0 === str.localeCompare([dt.getFullYear(), pad(1 + dt.getMonth()), pad(dt.getDate())].join('-'));_x000D_
}_x000D_
_x000D_
console.log(isDate("2018-08-09"));_x000D_
console.log(isDate("2008-23-03"));_x000D_
console.log(isDate("0000-00-00"));_x000D_
console.log(isDate("2002-02-29"));_x000D_
console.log(isDate("2004-02-29"));
_x000D_
_x000D_
_x000D_


 moment(dateString, 'YYYY-MM-DD', true).isValid() ||
 moment(dateString, 'YYYY-M-DD', true).isValid() ||
 moment(dateString, 'YYYY-MM-D', true).isValid();

You can use this one it's for YYYY-MM-DD. It checks if it's a valid date and that the value is not NULL. It returns TRUE if everythings check out to be correct or FALSE if anything is invalid. It doesn't get easier then this!

function validateDate(date) {
    var matches = /^(\d{4})[-\/](\d{2})[-\/](\d{2})$/.exec(date);
    if (matches == null) return false;
    var d = matches[3];
    var m = matches[2] - 1;
    var y = matches[1] ;
    var composedDate = new Date(y, m, d);
    return composedDate.getDate() == d &&
            composedDate.getMonth() == m &&
            composedDate.getFullYear() == y;
}

Be aware that months need to be subtracted like this: var m = matches[2] - 1; else the new Date() instance won't be properly made.


Here's the JavaScript rejex for YYYY-MM-DD format

/([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/


I recommend to use the Using jquery validation plugin and jquery ui date picker

jQuery.validator.addMethod("customDateValidator", function(value, element) {
// dd-mm-yyyy
   var re = /^([0]?[1-9]|[1|2][0-9]|[3][0|1])[./-]([0]?[1-9]|[1][0-2])[./-]([0-9]{4}|[0-9]{2})$/ ; 
   if (! re.test(value) ) return false
   // parseDate throws exception if the value is invalid
   try{jQuery.datepicker.parseDate( 'dd-mm-yy', value);return true ;}
   catch(e){return false;} 
   },
   "Please enter a valid date format dd-mm-yyyy"
);

this.ui.form.validate({
    debug: true,
    rules : {
    title : { required : true, minlength: 4 }, 
    date : { required: true, customDateValidator: true }
    }
}) ;

Using Jquery and date picker just create a function with

// dd-mm-yyyy
var re = /^([0]?[1-9]|[1|2][0-9]|[3][0|1])[./-]([0]?[1-9]|[1][0-2])[./-]([0-9]{4}|[0-9]{2})$/ ; 
 if (! re.test(value) ) return false
// parseDate throws exception if the value is invalid
try{jQuery.datepicker.parseDate( 'dd-mm-yy', value);return true ;}
catch(e){return false;}

You might use only the regular expression for validation

// dd-mm-yyyy
var re = /^([0]?[1-9]|[1|2][0-9]|[3][0|1])[./-]([0]?[1-9]|[1][0-2])[./-]([0-9]{4}|[0-9]{2})$/ ; 
return re.test(value) 

Of course the date format should be of your region


Since jQuery is tagged, here's an easy / user-friendly way to validate a field that must be a date (you will need the jQuery validation plugin):

html

<form id="frm">
<input id="date_creation" name="date_creation" type="text" />
</form>

jQuery

$('#frm').validate({
  rules: {
    date_creation: {
      required: true,
      date: true
    }
  }
});

DEMO + Example


UPDATE: After some digging, I found no evidence of a ready-to-go parameter to set a specific date format.

However, you can plug in the regex of your choice in a custom rule :)

$.validator.addMethod(
    "myDateFormat",
    function(value, element) {
        // yyyy-mm-dd
        var re = /^\d{4}-\d{1,2}-\d{1,2}$/;

        // valid if optional and empty OR if it passes the regex test
        return (this.optional(element) && value=="") || re.test(value);
    }
);

$('#frm').validate({
  rules: {
    date_creation: {
      // not optional
      required: true,
      // valid date
      date: true
    }
  }
});

This new rule would imply an update on your markup:

<input id="date_creation" name="date_creation" type="text" class="myDateFormat" />

try this Here is working Demo:

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

    if (dtArray == null) 
        return false;

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

    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;
}

});

changed regex is:

var rxDatePattern = /^(\d{4})(\/|-)(\d{1,2})(\/|-)(\d{1,2})$/; //Declare Regex

Working Demo fiddle here Demo

Changed your validation function to this

function isDate(txtDate)
{
return txtDate.match(/^d\d?\/\d\d?\/\d\d\d\d$/);
}

Rearrange the regex to:

/^(\d{4})([\/-])(\d{1,2})\2(\d{1,2})$/

I have done a little more than just rearrange the terms, I've also made it so that it won't accept "broken" dates like yyyy-mm/dd.

After that, you need to adjust your dtMonth etc. variables like so:

dtYear = dtArray[1];
dtMonth = dtArray[3];
dtDay = dtArray[4];

After that, the code should work just fine.


You could also just use regular expressions to accomplish a slightly simpler job if this is enough for you (e.g. as seen in [1]).

They are build in into javascript so you can use them without any libraries.

function isValidDate(dateString) {
  var regEx = /^\d{4}-\d{2}-\d{2}$/;
  return dateString.match(regEx) != null;
}

would be a function to check if the given string is four numbers - two numbers - two numbers (almost yyyy-mm-dd). But you can do even more with more complex expressions, e.g. check [2].

isValidDate("23-03-2012") // false
isValidDate("1987-12-24") // true
isValidDate("22-03-1981") // false
isValidDate("0000-00-00") // true