It is very easy to define custom validator in jQuery validation plugin.
For example, you have a form that contains two text input fields, you want to limit these two text input only accept a number ranging from 0 to 1000. Here is what you do:
1. Create a HTML markup. Note the input type is number, which will only accept number. You have to define the name attribute, this name will be referenced in step 3.
2. Define the custom validation method:
jQuery.validator.addMethod('range', function (value, element, param) {
return this.optional(element) || (value >= param[0] && value <= param[1]);
}, 'Please enter a range between 0 to 1000 !');
3. Apply custom validation
$("#myform").validate({
rules: {
field1: {
required: true,
range: [0, 1000],
}
}
});
4. Make sure your code is all contained within a
For example, you have a form that contains two text input fields, you want to limit these two text input only accept a number ranging from 0 to 1000. Here is what you do:
1. Create a HTML markup. Note the input type is number, which will only accept number. You have to define the name attribute, this name will be referenced in step 3.
2. Define the custom validation method:
jQuery.validator.addMethod('range', function (value, element, param) {
return this.optional(element) || (value >= param[0] && value <= param[1]);
}, 'Please enter a range between 0 to 1000 !');
3. Apply custom validation
$("#myform").validate({
rules: {
field1: {
required: true,
range: [0, 1000],
}
}
});
4. Make sure your code is all contained within a
document.ready
function.
Comments