简体   繁体   中英

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

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 want to show some custom error messages without adding an actual rule then you can use the showErrors() method, but if you are working on a hidden field it may not work

var validator = $( "<form-selector>" ).validate();

var errors = {};
$(".myHiddenField").each( function() {
    var $this = $(this);
    if($this.val() == "x") {
        errors[$this.attr('name')] = 'Some error message';
    }
});

validator.showErrors(errors);
$.validator.addMethod("NOTx", function(element,value) {
    return  value != "x";
}, 'warning word"!');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM