Sunday, October 10, 2010

Jquery Validation - DATE mm/dd/yyyy format

Experimenting with JQuery, I was asked to add certain validations for the form, DATE in mm/dd/yyyy format.

Well not very difficult, below is the code..


<-- Include JQuery -->

<script charset="utf-8" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>

<-- Include the Validation Plugin, NOTE - I have included from MS website instead of dev.jquery.com, it was down while working and throwing error in VALIDATOR method -->

<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.js"></script>

<-- Now add a Method to validate date in mm/dd/yyyy format with the regular expression -->

<script>
$(document).ready(function(){
    $.validator.addMethod("DateFormat", function(value,element) {
        return value.match(/^(0[1-9]|1[012])[- //.](0[1-9]|[12][0-9]|3[01])[- //.](19|20)\d\d$/);
            },
                "Please enter a date in the format mm/dd/yyyy"
            );
 $("#form5").validate({
        rules: {
            arrival: {
                required: true,
                DateFormat: true
            },
            departure : {
                required: true,
                DateFormat: true
            }
        }
    });
  });
</script>

That's all what is required ..

Note you can include the validation plugin from http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js as well, but as I wrote above it was down while writing this post.