April 26, 2010

Add a Custom Validation Method to the jQuery Validation Plugin




When it comes to Validation using jQuery, the jQuery Validation Plugin is my obvious choice. This plugin provides you with a number of pre-built validation logic. However if you need to build a custom validation method of your own, then here’s how to do so.

In the code shown below, we will add a custom validation method that checks to see if the Age entered is greater than 18. Please see that this is just a demonstration, so feel free to replace the code with a validation logic of your own

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>Quickly validate a field in jQuery</title>
<
script type="text/javascript"
src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js">
</
script>
<
script type="text/javascript" src=
"http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js">
</
script>
<
script type="text/javascript">
$(function() {
$.validator.addMethod('AgeGrtrEighteen', function(value) {
return parseFloat(value) > 0;
}, 'Age has to be greater than 18');

$('#form1').validate({
rules: {
age: {
AgeGrtrEighteen: true
}
}
});

});
</script>
</
head>
<
body>
<
form id="form1">
<
input id="age" name="age" type="text" />
<
input id="Submit1" type="submit" value="submit" />
</
form>
</
body>
</
html>

Now when you go ahead and enter a number less than 18 or a negative number in the field and submit the form, you get a validation error message as shown below:

Custom Validation jquery



'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

3 Responses to "Add a Custom Validation Method to the jQuery Validation Plugin"
  1. sandeeproop said...
    October 19, 2010 7:03 AM

    thx dude u solve my problem

  2. Anonymous said...
    June 17, 2011 8:29 AM

    Validation error is wrong. It should show
    "Age has to be greater than 18"

  3. Suprotim Agarwal said...
    June 17, 2011 12:11 PM

    Looks like the screenshot had a typo when it was taken. Everything else seems in order.

 

Copyright © 2009-2012 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions