Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a custom rule in jQuery Validate

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");
   }
});
like image 841
Jason Wells Avatar asked Jul 10 '13 02:07

Jason Wells


People also ask

How to validate a form with jQuery?

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.

Which example shows a custom Validation rule?

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.

How do you specify validation rules in HTML?

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.

How to add a custom class rule to a jQuery element?

); // 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";


1 Answers

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
        }
    }
});
like image 77
Nikko Reyes Avatar answered Sep 22 '22 10:09

Nikko Reyes