问题
I'm trying to use a custom validator with jQuery Validation plugin. However, I'm unsure how are you supposed to pass multiple arguments to a validation method? I've tried using (2,3), curly braces and combinations, but I have failed.
This is the code - ???? marks the area I need info about:
$(document).ready(function() {
jQuery.validator.addMethod("math", function(value, element, params) {
return this.optional(element) || value == params[0] + params[1];
}, jQuery.format("Please enter the correct value for {0} + {1}"));
$("#form_register").validate({
debug: true,
rules: {
inputEl: { required: true, math: ???? }
},
messages: {
inputEl: { required: "Required", math: "Incorrect result" }
}
});
});
回答1:
Javascript arrays:
[value1,value2,value3]
SO your code might be:
inputEl: { required: true, math: [2, 3 ,4 , 5] }
回答2:
You can also pass a normal JavaScript object as a parameter which I personally find easier to work with:
jQuery.validator.addMethod("myRule", function (value, element, options) {
return value === options.data;
}, "My Rule says no!");
$("#input").rules("add", { myRule: { data: "foo" } });
来源:https://stackoverflow.com/questions/1366858/jquery-validation-plugin-custom-method-multiple-parameters