I would like to add a custom rule to jQuery validate, and while I have checked the docs I have not been able to find out how to do this.
I want to loop over a set of hidden form fields. If the fields value is "X", then I would like to append an error class to a field.
So essentially this, but added as a rule to jQuery validate.
$(".myHiddenField").each( function() {
if($(this).val() == "x") {
$(this).closest(".foo").appendClass("error");
}
});
jQuery provides the plugin for validation for a library of rules for validations to help you validate your form elements, by selecting your complete form. All the creator has to do to achieve nearly perfect validations and to use this jQuery validation plugin, is to import the file into your HTML code and the script and use it, simple.
The example below shows a custom validation rule which checks that both a name and email are present. If the name is present the email must be present and vice versa. Example on left field validation. Example on right field validation.
There are several ways to specify validation rules. Validation methods with parameters can be specified as attributes (recommended) Validation methods without parameters can be specified as classes on the element. Both can be specified using the rules-option of the validate()-method.
); // connect it to a css class jQuery.validator.addClassRules ( { optdate : { optdate : true } }); addClassRules is a nice addition to the answer. You are able to create a custom rule and attach it to an element using the data attribute using the syntax data-rule-rulename="true";
You may use addMethod()
$.validator.addMethod('yourRuleName', function (value, element, param) {
//Your Validation Here
return isValid; // return bool here if valid or not.
}, 'Your error message!');
$('#myform').validate({
rules: {
field1: {
yourRuleName: true
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With