Validate date in dd/mm/yyyy format using JQuery Validate

213,102

Solution 1

You don't need the date validator. It doesn't support dd/mm/yyyy format, and that's why you are getting "Please enter a valid date" message for input like 13/01/2014. You already have the dateITA validator, which uses dd/mm/yyyy format as you need.

Just like the date validator, your code for dateGreaterThan and dateLessThan calls new Date for input string and has the same issue parsing dates. You can use a function like this to parse the date:

function parseDMY(value) {
    var date = value.split("/");
    var d = parseInt(date[0], 10),
        m = parseInt(date[1], 10),
        y = parseInt(date[2], 10);
    return new Date(y, m - 1, d);
}

Solution 2

This will also checks in leap year. This is pure regex, so it's faster than any lib (also faster than moment.js). But if you gonna use a lot of dates in ur code, I do recommend to use moment.js

var dateRegex = /^(?=\d)(?:(?:31(?!.(?:0?[2469]|11))|(?:30|29)(?!.0?2)|29(?=.0?2.(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(?:\x20|$))|(?:2[0-8]|1\d|0?[1-9]))([-.\/])(?:1[012]|0?[1-9])\1(?:1[6-9]|[2-9]\d)?\d\d(?:(?=\x20\d)\x20|$))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\x20[AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$/;

console.log(dateRegex.test('21/01/1986'));

enter image description here

http://regexper.com/....

Solution 3

If you use the moment js library it can easily be done like this -

jQuery.validator.addMethod("validDate", function(value, element) {
        return this.optional(element) || moment(value,"DD/MM/YYYY").isValid();
    }, "Please enter a valid date in the format DD/MM/YYYY");

Solution 4

I encountered a similar problem in my project. After struggling a lot, I found this solution:

if ($.datepicker.parseDate("dd/mm/yy","17/06/2015") > $.datepicker.parseDate("dd/mm/yy","20/06/2015"))
    // do something

You DO NOT NEED plugins like jQuery Validate or Moment.js for this issue. Hope this solution helps.

Solution 5

This validates dd/mm/yyy dates. Edit your jquery.validate.js and add these.

Reference(Regex): Regex to validate date format dd/mm/yyyy

dateBR: function( value, element ) {
    return this.optional(element) || /^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$/.test(value);
}

messages: {
    dateBR: "Invalid date."
}

classRuleSettings: {
    dateBR: {dateBR: true}
}

Usage:

$( "#myForm" ).validate({
    rules: {
        field: {
            dateBR: true
        }
    }
});
Share:
213,102
Cipher
Author by

Cipher

Updated on July 09, 2022

Comments

  • Cipher
    Cipher almost 2 years

    I am taking input of date of birth and date of death. Validation required

    1. date of death should be more than date of birth
    2. Date format to be dd/mm/yyyy
    3. Dates to be less than or equal to today.

    Validate doesn't work as expected and can't figure out the problem. Please help.

    Fiddle code

    JS libraries used

    1. JQuery UI for Calendar/Datepicker
    2. JQuery validate for form validation
    3. Additional methods for validation library

      var today = new Date();
      var authorValidator = $("#itemAuthorForm").validate({
      rules : {
          dateOfBirth : {
              required : false,
              date : true,
              dateITA : true,
              dateLessThan : '#expiredDate'
          },
          expiredDate : {
              required : false,
              date : true,
              dateITA : true,
              dateGreaterThan : "#dateOfBirth"
          }
      },
      onfocusout : function(element) {
          if ($(element).val()) {
              $(element).valid();
          }
      }
      });
      var dateOptionsDOE = {
      maxDate : today,
      dateFormat : "dd/mm/yy",
      changeMonth : true,
      changeYear : true,
      onClose : function(selectedDate) {
          $("#dateOfBirth").datepicker("option", "maxDate", selectedDate);
      }
      };
      var dateOptionsDOB = {
      maxDate : today,
      dateFormat : "dd/mm/yy",
      changeMonth : true,
      changeYear : true,
      onClose : function(selectedDate) {
          $("#expiredDate").datepicker("option", "minDate", selectedDate);
      }
       };
      
      jQuery.validator.addMethod("dateGreaterThan",
      function(value, element, params) {
      if ($(params).val() === "")
          return true;
      
      if (!/Invalid|NaN/.test(new Date(value))) {
          return new Date(value) > new Date($(params).val());
      }
      return isNaN(value) && isNaN($(params).val())
              || (Number(value) > Number($(params).val()));
              }, 'Must be greater than {0}.');
              jQuery.validator.addMethod("dateLessThan",
              function(value, element, params) {
      if ($(params).val() === "")
          return true;
      
      if (!/Invalid|NaN/.test(new Date(value))) {
          return new Date(value) < new Date($(params).val());
      }
      
      return isNaN(value) && isNaN($(params).val())
              || (Number(value) < Number($(params).val()));
              }, 'Must be less than {0}.');
              $("#expiredDate").datepicker(
          $.extend({}, $.datepicker.regional['en-GB'], dateOptionsDOE));
              $("#dateOfBirth").datepicker(
          $.extend({}, $.datepicker.regional['en-GB'], dateOptionsDOB));
      
  • Cipher
    Cipher almost 10 years
    Thank you for spending time to read through my code.Code seems to work after incorporating your suggestions. Bingo! :)... most of my time was consumed in finding additional methods for validator and also en-GB formatting for UI widgets. I should have removed date:true rule :)
  • Arkadiusz Kałkus
    Arkadiusz Kałkus over 8 years
    Kudos for this diagram and regex! Is it generated? Could you tell us what's the name of the tool if it is?
  • Leonardo Cavalcante
    Leonardo Cavalcante over 8 years
    here: regexper.com
  • RN Kushwaha
    RN Kushwaha almost 8 years
    It always returns a date even if I enter an invalid date.
  • cusman
    cusman almost 8 years
    Is there one for mm/dd/yyyy format?
  • Leonardo Cavalcante
    Leonardo Cavalcante almost 8 years
    cusman, in that case i'd use moment.js
  • Diego Cotini
    Diego Cotini over 7 years
    Simplest and functional solution. Thanks.
  • Organic
    Organic over 7 years
    But you need JQuery UI.
  • FrenkyB
    FrenkyB over 7 years
    Just like you've said - you don't need plugins. This simply works. If input is false, it throws exception. Thanks a lot :)
  • FrenkyB
    FrenkyB over 7 years
    What if you want to parse hours and minutes?
  • dinesh kandpal
    dinesh kandpal over 6 years
    when you are validating date in ''DD/MM/YYYY" Does it also include dateFormat : "dd-mm-yy" and dd.mm.yy ???
  • SharpC
    SharpC over 6 years
    Impressive! This even copes with the 100 and 400 year leap year changes.
  • angel
    angel over 6 years
    this not work if you write 12/13/1991 this shows as a fine date when a month 13th not exist
  • izstas
    izstas over 6 years
    This function is not designed to validate the date. The OP is already using a dateITA validator, and this function just aids in the implementation of additional dateGreaterThan and dateLessThan validators.
  • Yogurtu
    Yogurtu about 6 years
    If you add OR, will do the trick: return this.optional(element) || moment(value,"DD/MM/YYYY").isValid() || moment(value,"DD-MM-YYYY").isValid();
  • Shan
    Shan about 5 years
    This will fail for : moment(1,"DD/MM/YYYY").isValid(); moment will return true .
  • Jeremy Thompson
    Jeremy Thompson over 4 years
  • Hello Universe
    Hello Universe over 2 years
    One should not directly edit jQuery validate core files. It is dangerous