|
Adding custom validation rules to the JQuery Validation Plugin |
It comes with quite a few pre defined validation methods (you can see them here: http://docs.jquery.com/Plugins/Validation#List_of_built-in_Validation_methods), but what if one of your fields requires a bespoke validation type, for example matching the first N characters of a string.
Well its pretty easy to do, you just have to plan your new rule, and programatically add it to the plugin. In the example below I am going to match the string '123456' and check it as a rule, alongside the existing rules.
I'm assuming you have already imported the JQuery library and Validation plugin. Next we use the addMethod() function of the Validation plugin to add a new custom method. This accepts a few different arguments, as detailed below:
Name (String)
The name of the method, used to identify and referencing it, must be a valid javascript identifier
Method (Callback)
The actual method implementation, returning true if an element is valid. First argument: Current value. Second argument: Validated element. Third argument: Parameters.
Message (string / function)
The default message to display for this method. Can be a function created by jQuery.validator.format(value). When undefined, an already existing message is used (handy for localization), otherwise the field-specific messages have to be defined.
As an example I have created a new rule called 'pattern-match', this rule will check if the passed in element is required 'this.optional(element)' OR if the first six characters match the designated pattern, in this case '123456'.
2$(document).ready(function(){
3
4$.validator.addMethod("pattern-match", function(value, element) {
5
6return this.optional(element) || (value.substr(0,6) == '123456');
7
8}, "* match the string");
9
10});
11</script>
This code creates the new validation method, now we can reference it in our validate() method just like all the pre existing methods.
2$(document).ready(function(){
3
4$("#form").validate({
5
6errorContainer: "#error",
7errorLabelContainer: "#error ul",
8wrapper: "li",
9
10rules: {
11numberField: {
12
13required: true,
14pattern-match: true,
15minlength: 8,
16maxlength: 10 }
17 },
18
19messages: {
20
21numberField: {
22
23required: "Please enter a number",
24pattern-match: "Number does not match 123456",
25minlength: "Number must be at least 8 characters long",
26maxlength: "Number cannot be more than 10 characters long"
27}
28
29 }
30});
31
32});
33</script>
Just add it in with the other methods, and specify the the error message that goes with it.
The addMethod() function will take any form of custom validation that you can write in standard JavaScript, so it should be possible to accommodate any bizarre rules you might want to come up with.