[jquery] Custom date format with jQuery validation plugin

How can I specify a custom date formate to be validated with the Validation Plugin for jQuery?

This question is related to jquery validation datetime-format

The answer is


You can create your own custom validation method using the addMethod function. Say you wanted to validate "dd/mm/yyyy":

$.validator.addMethod(
    "australianDate",
    function(value, element) {
        // put your own logic here, this is just a (crappy) example
        return value.match(/^\d\d?\/\d\d?\/\d\d\d\d$/);
    },
    "Please enter a date in the format dd/mm/yyyy."
);

And then on your form add:

$('#myForm')
    .validate({
        rules : {
            myDate : {
                australianDate : true
            }
        }
    })
;

nickf's answer is good, but note that the validation plug-in already includes validators for several other date formats, in the additional-methods.js file. Before you write your own, make sure that someone hasn't already done it.


Is Easy, Example: Valid for HTML5 automatic type="date".

<script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js"></script>
<script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/additional-methods.min.js"></script>
<script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/localization/messages_es.js"></script>

$(function () {

        // Overload method default "date" jquery.validate.min.js
        $.validator.addMethod(
            "date",
            function(value, element) {
                var dateReg = /^\d{2}([./-])\d{2}\1\d{4}$/;
                return value.match(dateReg);
            },
            "Invalid date"
        );

     // Form Demo jquery.validate.min.js
     $('#form-datos').validate({
        submitHandler: function(form) {
            form.submit();
        }
    });

});

Here is an example for a new validation method that will validate almost any date format, including:

  • dd/mm/yy or dd/mm/yyyy
  • dd.mm.yy or dd.mm.yyyy
  • dd,mm,yy or dd,mm,yyyy
  • dd mm yy or dd mm yyyy
  • dd-mm-yy or dd-mm-yyyy

Then, when you pass the value to the php you can convert it with strtotime

Here is how to add the method:

    $.validator.addMethod("anyDate",
    function(value, element) {
        return value.match(/^(0?[1-9]|[12][0-9]|3[0-1])[/., -](0?[1-9]|1[0-2])[/., -](19|20)?\d{2}$/);
    },
    "Please enter a date in the format!"
);

Then you add the new filter with:

$('#myForm')
.validate({
    rules : {
        field: {
            anyDate: true
        }
    }
})

;


I personally use the very good http://www.datejs.com/ library.

Docco here: http://code.google.com/p/datejs/wiki/APIDocumentation

You can use the following to get your Australian format and will validate the leap day 29/02/2012 and not 29/02/2011:

jQuery.validator.addMethod("australianDate", function(value, element) { 
    return Date.parseExact(value, "d/M/yyyy");
});

$("#myForm").validate({
   rules : {
      birth_date : { australianDate : true }
   }
});

I also use the masked input plugin to standardise the data http://digitalbush.com/projects/masked-input-plugin/

$("#birth_date").mask("99/99/9999");

nickf's answer is good, but note that the validation plug-in already includes validators for several other date formats, in the additional-methods.js file. Before you write your own, make sure that someone hasn't already done it.


$.validator.addMethod("mydate", function (value, element) {

        return this.optional(element) || /^(\d{4})(-|\/)(([0-1]{1})([1-2]{1})|([0]{1})([0-9]{1}))(-|\/)(([0-2]{1})([1-9]{1})|([3]{1})([0-1]{1}))/.test(value);

    });

you can input like yyyy-mm-dd also yyyy/mm/dd

but can't judge the the size of the month sometime Feb just 28 or 29 days.


Jon, you have some syntax errors, see below, this worked for me.

  <script type="text/javascript">
$(document).ready(function () {

  $.validator.addMethod(
      "australianDate",
      function (value, element) {
        // put your own logic here, this is just a (crappy) example 
        return value.match(/^\d\d?\/\d\d?\/\d\d\d\d$/);
      },
      "Please enter a date in the format dd/mm/yyyy"
    );

  $('#testForm').validate({
    rules: {
      "myDate": {
        australianDate: true
      }
    }
  });

});             


This is me combining/modifying previous posts to achieve my desired result:

        // Override built-in date validator
        $.validator.addMethod(
            "date",
            function (value, element) {
                //Return            NB: isRequired is not checked at this stage
                return (value=="")? true : isDate(value);
            },
            "* invalid"
        );

Add Date validation after your validation config. I.e. after calling the $(form).validate({ ... }) method.

        //Add date validation (if applicable)
        $('.date', $(frmPanelBtnId)).each(function () {
            $(this).rules('add', {
                date: true
            });
        });

Finally, the main isDate Javascript function modified for UK Date Format

//Validates a date input -- http://jquerybyexample.blogspot.com/2011/12/validate-date-    using-jquery.html
function isDate(txtDate) {
    var currVal = txtDate;
    if (currVal == '')
       return false;

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

  if (dtArray == null)
      return false;

   //Checks for dd/mm/yyyy format.
   var dtDay = dtArray[1];
   var dtMonth = dtArray[3];
   var 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;
}

Here's a specific code sample which worked for me recently:

// Replace the builtin US date validation with UK date validation
$.validator.addMethod(
    "date",
    function ( value, element ) {
        var bits = value.match( /([0-9]+)/gi ), str;
        if ( ! bits )
            return this.optional(element) || false;
        str = bits[ 1 ] + '/' + bits[ 0 ] + '/' + bits[ 2 ];
        return this.optional(element) || !/Invalid|NaN/.test(new Date( str ));
    },
    "Please enter a date in the format dd/mm/yyyy"
);

I should note that this actually replaces the built-in date validation routine, though I couldn't see that this should cause an issue with the current plugin.

I then applied this to the form using:

$( '#my_form input.date' ).rules( 'add', { date: true } );

Here is an example for a new validation method that will validate almost any date format, including:

  • dd/mm/yy or dd/mm/yyyy
  • dd.mm.yy or dd.mm.yyyy
  • dd,mm,yy or dd,mm,yyyy
  • dd mm yy or dd mm yyyy
  • dd-mm-yy or dd-mm-yyyy

Then, when you pass the value to the php you can convert it with strtotime

Here is how to add the method:

    $.validator.addMethod("anyDate",
    function(value, element) {
        return value.match(/^(0?[1-9]|[12][0-9]|3[0-1])[/., -](0?[1-9]|1[0-2])[/., -](19|20)?\d{2}$/);
    },
    "Please enter a date in the format!"
);

Then you add the new filter with:

$('#myForm')
.validate({
    rules : {
        field: {
            anyDate: true
        }
    }
})

;


nickf's answer is good, but note that the validation plug-in already includes validators for several other date formats, in the additional-methods.js file. Before you write your own, make sure that someone hasn't already done it.


I personally use the very good http://www.datejs.com/ library.

Docco here: http://code.google.com/p/datejs/wiki/APIDocumentation

You can use the following to get your Australian format and will validate the leap day 29/02/2012 and not 29/02/2011:

jQuery.validator.addMethod("australianDate", function(value, element) { 
    return Date.parseExact(value, "d/M/yyyy");
});

$("#myForm").validate({
   rules : {
      birth_date : { australianDate : true }
   }
});

I also use the masked input plugin to standardise the data http://digitalbush.com/projects/masked-input-plugin/

$("#birth_date").mask("99/99/9999");

This is me combining/modifying previous posts to achieve my desired result:

        // Override built-in date validator
        $.validator.addMethod(
            "date",
            function (value, element) {
                //Return            NB: isRequired is not checked at this stage
                return (value=="")? true : isDate(value);
            },
            "* invalid"
        );

Add Date validation after your validation config. I.e. after calling the $(form).validate({ ... }) method.

        //Add date validation (if applicable)
        $('.date', $(frmPanelBtnId)).each(function () {
            $(this).rules('add', {
                date: true
            });
        });

Finally, the main isDate Javascript function modified for UK Date Format

//Validates a date input -- http://jquerybyexample.blogspot.com/2011/12/validate-date-    using-jquery.html
function isDate(txtDate) {
    var currVal = txtDate;
    if (currVal == '')
       return false;

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

  if (dtArray == null)
      return false;

   //Checks for dd/mm/yyyy format.
   var dtDay = dtArray[1];
   var dtMonth = dtArray[3];
   var 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;
}

@blasteralfred:

I got following rule validating correct date for me (DD MM YYYY)

jQuery.validator.addMethod(
"validDate",
function(value, element) {
    return value.match(/(?:0[1-9]|[12][0-9]|3[01]) (?:0[1-9]|1[0-2]) (?:19|20\d{2})/);
},
"Please enter a valid date in the format DD MM YYYY"

);

For DD/MM/YYYY

jQuery.validator.addMethod(
"validDate",
function(value, element) {
    return value.match(/(?:0[1-9]|[12][0-9]|3[01])\/(?:0[1-9]|1[0-2])\/(?:19|20\d{2})/);
},
"Please enter a valid date in the format DD/MM/YYYY"

);

This will not validate 01 13 2017 and 01/13/2017.

And also does not validate 50 12 2017 and 50/12/2017.


nickf's answer is good, but note that the validation plug-in already includes validators for several other date formats, in the additional-methods.js file. Before you write your own, make sure that someone hasn't already done it.


@blasteralfred:

I got following rule validating correct date for me (DD MM YYYY)

jQuery.validator.addMethod(
"validDate",
function(value, element) {
    return value.match(/(?:0[1-9]|[12][0-9]|3[01]) (?:0[1-9]|1[0-2]) (?:19|20\d{2})/);
},
"Please enter a valid date in the format DD MM YYYY"

);

For DD/MM/YYYY

jQuery.validator.addMethod(
"validDate",
function(value, element) {
    return value.match(/(?:0[1-9]|[12][0-9]|3[01])\/(?:0[1-9]|1[0-2])\/(?:19|20\d{2})/);
},
"Please enter a valid date in the format DD/MM/YYYY"

);

This will not validate 01 13 2017 and 01/13/2017.

And also does not validate 50 12 2017 and 50/12/2017.


Is Easy, Example: Valid for HTML5 automatic type="date".

<script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js"></script>
<script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/additional-methods.min.js"></script>
<script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/localization/messages_es.js"></script>

$(function () {

        // Overload method default "date" jquery.validate.min.js
        $.validator.addMethod(
            "date",
            function(value, element) {
                var dateReg = /^\d{2}([./-])\d{2}\1\d{4}$/;
                return value.match(dateReg);
            },
            "Invalid date"
        );

     // Form Demo jquery.validate.min.js
     $('#form-datos').validate({
        submitHandler: function(form) {
            form.submit();
        }
    });

});

$.validator.addMethod("mydate", function (value, element) {

        return this.optional(element) || /^(\d{4})(-|\/)(([0-1]{1})([1-2]{1})|([0]{1})([0-9]{1}))(-|\/)(([0-2]{1})([1-9]{1})|([3]{1})([0-1]{1}))/.test(value);

    });

you can input like yyyy-mm-dd also yyyy/mm/dd

but can't judge the the size of the month sometime Feb just 28 or 29 days.


Here's a specific code sample which worked for me recently:

// Replace the builtin US date validation with UK date validation
$.validator.addMethod(
    "date",
    function ( value, element ) {
        var bits = value.match( /([0-9]+)/gi ), str;
        if ( ! bits )
            return this.optional(element) || false;
        str = bits[ 1 ] + '/' + bits[ 0 ] + '/' + bits[ 2 ];
        return this.optional(element) || !/Invalid|NaN/.test(new Date( str ));
    },
    "Please enter a date in the format dd/mm/yyyy"
);

I should note that this actually replaces the built-in date validation routine, though I couldn't see that this should cause an issue with the current plugin.

I then applied this to the form using:

$( '#my_form input.date' ).rules( 'add', { date: true } );

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to validation

Rails 2.3.4 Persisting Model on Validation Failure Input type number "only numeric value" validation How can I manually set an Angular form field as invalid? Laravel Password & Password_Confirmation Validation Reactjs - Form input validation Get all validation errors from Angular 2 FormGroup Min / Max Validator in Angular 2 Final How to validate white spaces/empty spaces? [Angular 2] How to Validate on Max File Size in Laravel? WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to datetime-format

How do I convert 2018-04-10T04:00:00.000Z string to DateTime? Unable to obtain LocalDateTime from TemporalAccessor when parsing LocalDateTime (Java 8) How can I create basic timestamps or dates? (Python 3.4) Format Instant to String Laravel $q->where() between dates How to Convert datetime value to yyyymmddhhmmss in SQL server? AngularJS - convert dates in controller Display DateTime value in dd/mm/yyyy format in Asp.NET MVC Display date in dd/mm/yyyy format in vb.net Convert DataFrame column type from string to datetime, dd/mm/yyyy format