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

3 comments:

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

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

    ReplyDelete