Java Ninja Chronicles By Norris Shelton

Things I learned in the pursuit of code

My previous blog entry showed how to quickly add Jquery Validation. One that was not there was the ability to compare two fields that contain dates and validate that the field that should hold the older date was in-fact older. Here is how I created the custom validation.

First I defined the custom validation called dateRange and it’s error message. This allows me to dateRange as a CSS class name for validation purposes.

<script type="text/javascript">
     $(document).ready(function() {
        $.validator.addMethod("dateRange", function() {
            return new Date($("#olderDate").val()) < new Date($("#newerDate").val());
        }, "Please specify a correct date range<br/>The older date must be before the newer date.");

Then I set-up the form for validation. I added the groups option so that the plugin knows that the fields should be validated together. Without this validation, each field will be validated and if the validation failed, both fields would have error messages.

            groups: {
                dateRange: "olderDate newerDate"

All that is left is the HTML of the actual form. Here I create a form that has two input fields. I indicate that both fields are required, they must be dates and they should be in the correct chronological order.

<form name="myForm" id="myForm" action="">
     <input class="required date dateRange" type="text" id="olderDate" name="olderDate">
     <input class="required date dateRange" type="text" id="newerDate" name="newerDate">
     <input type="submit" value="Let's date validate"/>

December 15th, 2010

Posted In: javascript, JQuery

Tags: , , ,

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

WP to LinkedIn Auto Publish Powered By :