0

我为 jQuery Validation 编写了以下简单规则:

        jQuery.validator.addMethod("notEqual", function(value, element, param) 
        {
          return this.optional(element) || value != param;
        }, "This field is required");

这样我可以说:

        $("#form").validate({
                rules: 
                {
                    field1: {notEqual: "Please Select", required: true},
                    field2: {notEqual: "Year", required: true}
                },
                messages: 
                {
                    field1: {
                            notEqual: "This field is required", 
                            required: "This field is required"
                            }
                    field2: {
                            notEqual: "This field is required", 
                            required: "This field is required"
                            }
                },

                submitHandler: function(form) {
                form.submit();
            }
        }); 

但是我想说任何一个字段都不允许等于多个事物,例如

field1: {notEqual: "Please Select" || "Year" || "Some Value", required: true},

但是我已经尝试过这种语法以及其他一些排列“ÖR”运算符的方法,但它们都不起作用。任何人都可以帮忙吗?谢谢。

4

1 回答 1

1

您可以将 JavaScript 数组作为参数传递给验证方法,如对jQuery Validation 插件自定义方法的回答中所述。多个参数

例如

field1: {notEqual: ["Please Select", "Year", "Some Value"], required: true},

然后让你的自定义方法像这样

 jQuery.validator.addMethod("notEqual", function(value, element, param) 
 {
  var result = value != param[0] && value != param[1] && value != param[2]; 
  return this.optional(element) || result;
 }, "This field is required");
于 2012-11-27T22:15:15.643 回答