jquery.validate Better Date Method

The jquery.validate plugin currently has the validation method “date” which will correctly validate the format “xx/xx/xxxx”. However you can enter a date such as “40/01/2011” and it will pass. Obviously there is no month 40 or even day 40.

Borrowing from the “dateITA” validation method in the additional-methods.js I created a “dateUS” validation method that will detect for not only a correctly US formatted date but a valid date as well using the “mm/dd/yyyy” format.

Add this to your additional-methods.js file or load in another methods file (ex:my-methods.js):

/**
  * Return true, if the value is a valid date, also making this formal check mm/dd/yyyy.
  *
  * @example jQuery.validator.methods.date("01/01/1900")
  * @result true
  *
  * @example jQuery.validator.methods.date("13/01/1990")
  * @result false
  *
  * @example jQuery.validator.methods.date("01.01.1900")
  * @result false
  *
  * @example <input name="pippo" class="dateUS" />
  * @desc Declares an optional input element whose value must be a valid date.
  *
  * @name jQuery.validator.methods.dateUS
  * @type Boolean
  * @cat Plugins/Validate/Methods
  */

jQuery.validator.addMethod(
	"dateUS",
	function(value, element) {
		var check = false;
		var re = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
		if( re.test(value)){
			var adata = value.split('/');
			var mm = parseInt(adata[0],10);
			var dd = parseInt(adata[1],10);
			var yyyy = parseInt(adata[2],10);
			var xdata = new Date(yyyy,mm-1,dd);
			if ( ( xdata.getFullYear() == yyyy ) && ( xdata.getMonth () == mm - 1 ) && ( xdata.getDate() == dd ) )
				check = true;
			else
				check = false;
		} else
			check = false;
		return this.optional(element) || check;
	},
	"Please enter a date in the format mm/dd/yyyy"
);

Use “dateUS” as your validation method.
Example: <input type=”text” class=”dateUS” name=”myDate”>