Rectangle 27 56

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.

This should be on top

setting the rule dateISO: true, validates date in the format yyy-mm-dd

Custom date format with jQuery validation plugin - Stack Overflow

jquery validation datetime-format
Rectangle 27 56

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.

This should be on top

setting the rule dateISO: true, validates date in the format yyy-mm-dd

Custom date format with jQuery validation plugin - Stack Overflow

jquery validation datetime-format
Rectangle 27 16

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

  • 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
        }
    }
})
mmm
/^(0?[1-9]|[12][0-9]|3[0-1])[/., -](0?[1-9]|1[0-2]|[a-zA-Z]{3})[/., -](19|20)?\d{2}$/

Custom date format with jQuery validation plugin - Stack Overflow

jquery validation datetime-format
Rectangle 27 16

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

  • 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
        }
    }
})
mmm
/^(0?[1-9]|[12][0-9]|3[0-1])[/., -](0?[1-9]|1[0-2]|[a-zA-Z]{3})[/., -](19|20)?\d{2}$/

Custom date format with jQuery validation plugin - Stack Overflow

jquery validation datetime-format
Rectangle 27 26

if (Date.parse("some string")) {
   //Valid date
} else {
  //Not a valid date
}

can you please elaborate a little more?

This is not correct, as it returns number instead of NaN for e.g. 2014-11-31 which doesn't exist.

jQuery/JavaScript: Is it a date? (Validate whether is a date) - Stack ...

javascript jquery validation date datepicker
Rectangle 27 26

if (Date.parse("some string")) {
   //Valid date
} else {
  //Not a valid date
}

can you please elaborate a little more?

This is not correct, as it returns number instead of NaN for e.g. 2014-11-31 which doesn't exist.

jQuery/JavaScript: Is it a date? (Validate whether is a date) - Stack ...

javascript jquery validation date datepicker
Rectangle 27 60

You want to use this function along with the target date format and the strict parsing parameter to true (otherwise your validation might not be consistent) to delegate to the library all the needed checks:

var dateFormat = "DD/MM/YYYY";
moment("28/02/2011", dateFormat, true).isValid(); // return true
moment("29/02/2011", dateFormat, true).isValid(); // return false: February 29th of 2011 does not exist

I think this answer should be the accepted answer. The isValid() function is able to handle things like leap years and such and you're not doing all the string comparisons like in the currently accepted answer.

You may need to use the 3rd argument as well: As of version 2.3.0, you may specify a boolean for the last argument to make Moment use strict parsing. stackoverflow.com/questions/19978953/

var dateFormat = 'DD.MM.YYYY'; var givendate = '12'; alert(moment(givendate, dateFormat).isValid()); // true! alert(moment(givendate, dateFormat, true).isValid()); // false

this is checking only format. 30/02/2016 is not a valid date.but moment isValid() function return true

javascript - How to test a string is valid date or not using moment? -...

javascript jquery validation date momentjs
Rectangle 27 5

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

Custom date format with jQuery validation plugin - Stack Overflow

jquery validation datetime-format
Rectangle 27 5

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

Custom date format with jQuery validation plugin - Stack Overflow

jquery validation datetime-format
Rectangle 27 6

You can add a validation method to set max date as current date using addMethod as this

$.validator.addMethod("maxDate", function(value, element) {
    var curDate = new Date();
    var inputDate = new Date(value);
    if (inputDate < curDate)
        return true;
    return false;
}, "Invalid Date!");   // error message
$("#frm").validate({
    rules: {
        reportDate: {
            required: true,
            date: true,
            maxDate: true
        }
    }
});
'12/03/2013'
'mm/dd/yyyy'
12/03/2013 > 06/26/2013 (today's date)

javascript - Max Date using JQuery Validation - Stack Overflow

javascript jquery validation jquery-validate
Rectangle 27 26

Yes, you could use momentjs to parse it and compare it back with the string

function isValidDate(str) {
  var d = moment(str,'D/M/YYYY');
  if(d == null || !d.isValid()) return false;

  return str.indexOf(d.format('D/M/YYYY')) >= 0 
      || str.indexOf(d.format('DD/MM/YYYY')) >= 0
      || str.indexOf(d.format('D/M/YY')) >= 0 
      || str.indexOf(d.format('DD/MM/YY')) >= 0;
}
tests = ['',' ','x','1/1','1/12/2015','1/12/2015 1:00 PM']
for(var z in tests) {
  var test = tests[z];
  console.log('"' + test + '" ' + isValidDate(test));
}
"" false
 " " false
 "x" false
 "1/1" false
 "1/12/2015" true
 "1/12/2015 1:00 PM" true

For some reason with this code "2/22/2009" is not a valid date.

M/D/YYYY
D/M/YYYY

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

javascript - How to test a string is valid date or not using moment? -...

javascript jquery validation date momentjs
Rectangle 27 4

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

});

Custom date format with jQuery validation plugin - Stack Overflow

jquery validation datetime-format
Rectangle 27 4

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

});

Custom date format with jQuery validation plugin - Stack Overflow

jquery validation datetime-format
Rectangle 27 7

jQuery.validator.addMethod("customDateValidator",
    function(value, element) {
        try { jQuery.datepicker.parseDate("mm/dd/yyyy", value); return true; }
        catch(e) { 
            return false;
        }
    },
    "Please enter a valid date"
);

$("input[name='date']").rules("add", { customDateValidator:true });

can you please give me a jsFiddle example? -I tried your answer and could not make it work by myself =(

If you're using datepicker anyway (you probably are), this seems like a better validator than just simply using Date.parse

"mm/dd/yy"

I've never seen the jQuery validator put to use. Very cool. Upvote for you. Thanks

jQuery/JavaScript: Is it a date? (Validate whether is a date) - Stack ...

javascript jquery validation date datepicker
Rectangle 27 7

jQuery.validator.addMethod("customDateValidator",
    function(value, element) {
        try { jQuery.datepicker.parseDate("mm/dd/yyyy", value); return true; }
        catch(e) { 
            return false;
        }
    },
    "Please enter a valid date"
);

$("input[name='date']").rules("add", { customDateValidator:true });

can you please give me a jsFiddle example? -I tried your answer and could not make it work by myself =(

If you're using datepicker anyway (you probably are), this seems like a better validator than just simply using Date.parse

"mm/dd/yy"

I've never seen the jQuery validator put to use. Very cool. Upvote for you. Thanks

jQuery/JavaScript: Is it a date? (Validate whether is a date) - Stack ...

javascript jquery validation date datepicker
Rectangle 27 5

Use the Date.parse() method to check if a date is valid:

var timestamp = Date.parse($("input[name='date']").val()) 

if (isNaN(timestamp) == false) { 
    var d = new Date(timestamp); 
}

Date.parse has inconsistent implementations across browsers, and I wouldn't use it as a validator. For example, integers +-20,000 or so are valid Dates (Date.parse("200000")), but I wouldn't want to accept that as input.

and it neither validates if the date is valid, only checks that day is between 1 and 31, month between 1 and 12, etc. Date.parse('2000-11-31') == Date.parse('2000-12-01')

I would use: if(isNaN(Date.parse($("input[name='date']").val()){isNotDate}, writing less code should be the overall goal, atleast it is for me.

@TGarrett, don't you think that readable, maintainable code should be the goal?

@jameshill, yes'sir, readability is a huge concern when it comes to all code and having the developer after you who will make changes to your code, should be super easy for them to pick up, no matter what coding level the person may be at. What I did, was cleaned up the pieces that seemed redundant to me, such as having an equal operator for a bolean when you can simply remove that and add in any logic operator in there such as "!", for most who have been programming a for some time(1-2years), will be able to pick-up on it very fast. Different coding styles are another discussion that happens:

jQuery/JavaScript: Is it a date? (Validate whether is a date) - Stack ...

javascript jquery validation date datepicker
Rectangle 27 5

Use the Date.parse() method to check if a date is valid:

var timestamp = Date.parse($("input[name='date']").val()) 

if (isNaN(timestamp) == false) { 
    var d = new Date(timestamp); 
}

Date.parse has inconsistent implementations across browsers, and I wouldn't use it as a validator. For example, integers +-20,000 or so are valid Dates (Date.parse("200000")), but I wouldn't want to accept that as input.

and it neither validates if the date is valid, only checks that day is between 1 and 31, month between 1 and 12, etc. Date.parse('2000-11-31') == Date.parse('2000-12-01')

I would use: if(isNaN(Date.parse($("input[name='date']").val()){isNotDate}, writing less code should be the overall goal, atleast it is for me.

@TGarrett, don't you think that readable, maintainable code should be the goal?

@jameshill, yes'sir, readability is a huge concern when it comes to all code and having the developer after you who will make changes to your code, should be super easy for them to pick up, no matter what coding level the person may be at. What I did, was cleaned up the pieces that seemed redundant to me, such as having an equal operator for a bolean when you can simply remove that and add in any logic operator in there such as "!", for most who have been programming a for some time(1-2years), will be able to pick-up on it very fast. Different coding styles are another discussion that happens:

jQuery/JavaScript: Is it a date? (Validate whether is a date) - Stack ...

javascript jquery validation date datepicker
Rectangle 27 10

This workaround appears to handle chrome and ie etc. In chrome I cannot type in an incorrect date so the date picker will give me a valid date and when it passes it to the validator function it will be in the yyyy-mm-dd format. i.e lets me type straight into the input or use the picker, typing in an invalid date i.e. 2/30/2013 (invalid in en-GB culture) it correctly invalidates it and prevents further progress. If no better suggestions I think ill go with this as the best workable answer

$(document).ready(function () {
$.culture = Globalize.culture("en-GB");
$.validator.methods.date = function (value, element) {
    //This is not ideal but Chrome passes dates through in ISO1901 format regardless of locale 
    //and despite displaying in the specified format.

    return this.optional(element)
        || Globalize.parseDate(value, "dd/mm/yyyy", "en-GB")
        || Globalize.parseDate(value, "yyyy-mm-dd");
}});

Thanks for this, been banging my head against a wall all day and this worked a charm. Incidentally I couldn't get it to work with latest version of Globalize.js (v1.1.0) since it's all changed to CLDR. Works fine with an older version v0.1.1 though.

jquery - Unobtrusive Validation on en-GB Dates - Stack Overflow

jquery asp.net-mvc asp.net-mvc-4 unobtrusive-validation jquery-globalization
Rectangle 27 123

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."
);
$('#myForm')
    .validate({
        rules : {
            myDate : {
                australianDate : true
            }
        }
    })
;
// put your own logic here, this is just a (crappy) example

Custom date format with jQuery validation plugin - Stack Overflow

jquery validation datetime-format
Rectangle 27 123

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."
);
$('#myForm')
    .validate({
        rules : {
            myDate : {
                australianDate : true
            }
        }
    })
;
// put your own logic here, this is just a (crappy) example

Custom date format with jQuery validation plugin - Stack Overflow

jquery validation datetime-format