Wednesday, September 1, 2010

Custom jQuery Validate Rule For Making Sure One Date is Later Than Another

In addition to providing a number of standard validation rules, the jQuery Validation plugin also allows you to create your own validation rules via the addMethod() function.  Today I had a situation where I had to use that function:  I had to create a rule to ensure that the end date of a date range determined by the user was later than the starting date.  I thought I'd share what I came up with.

The details of the situation:

  • The user set the starting date using two radio buttons and a text field bound to the jQuery UI Datepicker.  Selecting the first radio button meant that the start date (the "now" button) should be set to the current date, while selecting the second radio button (the "later" button) meant that the starting date would be determined by the value in the Datepicker field.
  • The user set the ending date using another Datepicker-bound text field.
  • The Datepicker plugin ensures that the date is always in the format "mm/dd/yyyy".

Here is the code:


So if the user selected the second start date option and chose a date using the Datepicker widget, the code splits up the date string into an array and uses the individual month, day, and year values to create a Date object. If the user selects the option of making today the starting date, a new Date object is created (which by default has the value of the current date and time) and the code creates a new Date object with the same date but with the time-specific data stripped out (because the end date will not have a time value attached to it).

The Date object for the end date is created with the same technique used for the second start date option, and then the getTime() function is used on both the start and end Date objects to get the number of milliseconds between each date and January 1, 1970 (a starting point for date and time values used in both JavaScript and Java). Then it does the comparison between the two dates.

It's then a simple matter of applying this custom method somewhere within the normal jQuery Validation rules block:

rules: {
    endDate: {
      required: true,
      dateComparison: true