Thursday, December 1, 2011

jquery.validate and .rules

Jitendra wrote something cool which I assume is empowered by jquery.validate-vsdoc.js. It is:

$.validator.addMethod(

   "compareDate",

   function (value, element, comparewith) {

      if (value != '')

         var date1 = Globalize.parseDate(value, textBoxDateFormat).getTime();

      if (comparewith != '')

         var date2 = Globalize.parseDate(comparewith, textBoxDateFormat).getTime();

         

      if (date1 != undefined && date2 != undefined)

         return !(date1 > date2)

      else

         return false;

   }

);

 
 

It is implemented in jQuery like so:

var firstShipDateField = $('#SiliconSampleDefinition_FirstShipDate');

var lastShipDateField = $('#SiliconSampleDefinition_LastShipDate');

if (firstShipDateField.val() == '') {

   firstShipDateField.rules("remove");

} else {

   firstShipDateField.rules("add", {

      compareDate: lastShipDateField.val(),

      messages: { compareDate: "I'm Angry!" }

   });

}

 
 

On the C# side we will have:

@Html.CalendarFor(model => model.Foo.FirstShipDate, "/calendar.gif")

@Html.ValidationMessageFor(model => model.Foo.FirstShipDate)

 
 

The ValidationMessageFor will end up displaying "I'm Angry."

No comments:

Post a Comment