Creating a custom rule in jQuery Validate

javascript, jquery, validation

Solution

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
        }
    }
});

Problem

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"); } }); ```

Original source