【问题标题】:How can we specify rules for jquery validation plugin by class?我们如何按类指定 jquery 验证插件的规则?
【发布时间】:2012-03-16 17:20:20
【问题描述】:

jQuery Validation plugin 效果很好,而且非常易于使用:

$(".selector").validate({
})

只需设置“必填邮件”之类的css类,就会显示默认消息。

但是,我需要自定义消息。文档说您可以使用键值对为元素及其相应消息指定规则:

$(".selector").validate({
   rules: {
     name: "required",
     email: {
       required: true,
       email: true
     }
   },
   messages: {
     name: "Please specify your name",
     email: {
       required: "We need your email address to contact you",
       email: "Your email address must be in the format of name@domain.com"
     }
   }
})

但是,为每个表单元素指定规则是不切实际的,尤其是在 ASP.NET 中服务器生成的控件。是否可以指定适用于所有元素的规则?或者我可以以某种方式使用类选择器吗?

我尝试了以下方法,但没有成功:

$("#frmMyForm").validate
({
    rules:
    {
        $(".required email"):
        {
            required: true,
            email: true
        }
    },
    messages:
    {
        $(".required email"):
        {
            required: "Please enter your email address",
            email: "Your email address must be in the format of name@domain.com"
        }
    }
});

这似乎有语法错误 - 插件没有做任何事情。然后我尝试了:

$("#frmMyForm").validate
({
    rules:
    {
        ".required email":
        {
            required: true,
            email: true
        }
    },
    messages:
    {
        ".required email":
        {
            required: "Please enter your email address",
            email: "Your email address must be in the format of name@domain.com"
        }
    }
});

这没有任何语法错误 - 插件工作,但它忽略了规则/自定义消息。这里有人用过 jQuery Validation 插件吗?如果是这样,您是如何将规则/自定义消息应用于多个元素的?

谢谢!

【问题讨论】:

  • 我想既然我们有源代码,我可以在那里更改消息。但如果能够为不同的类提供不同的消息,或者我们可以将其应用于多个元素的机制,那就太好了。
  • 到目前为止的答案有什么问题吗?
  • 对不起,我还在尝试它们。我遇到了一些与验证组相关的意外并发症(我将作为一个单独的问题提出)。我今天将结束这个问题 - 我总是结束我提出的所有问题。感谢您的所有帮助。

标签: jquery jquery-validate


【解决方案1】:

就我的示例而言,这是基本的起始代码:

HTML:

<input type="text" name="field_1" />
<input type="text" name="field_2" />
<input type="text" name="field_3" />

JS:

$('#myForm').validate({
    rules: {
        field_1: {
            required: true,
            number: true
        },
        field_2: {
            required: true,
            number: true
        },
        field_3: {
            required: true,
            number: true
        }
    }
});

演示http://jsfiddle.net/rq5ra/


注意:无论使用以下哪种技术来分配规则,插件的绝对要求是每个元素都有一个唯一 name 属性。


选项 1a) 您可以根据所需的通用规则将类分配给您的字段,然后将这些规则分配给类。您还可以分配自定义消息。

HTML:

<input type="text" name="field_1" class="num" />
<input type="text" name="field_2" class="num" />
<input type="text" name="field_3" class="num" />

.rules() 方法必须在调用.validate()

之后调用

JS:

$('#myForm').validate({
    // your other plugin options
});

$('.num').each(function() {
    $(this).rules('add', {
        required: true,
        number: true,
        messages: {
            required:  "your custom message",
            number:  "your custom message"
        }
    });
});

演示http://jsfiddle.net/rq5ra/1/

选项 1b) 同上,但不使用class,而是匹配名称属性的公共部分:

$('[name*="field"]').each(function() {
    $(this).rules('add', {
        required: true,
        number: true,
        messages: { // optional custom messages
            required:  "your custom message",
            number:  "your custom message"
        }
    });
});

演示http://jsfiddle.net/rq5ra/6/


选项 2a) 您可以提取规则组并将它们组合成公共变量。

var ruleSet1 = {
        required: true,
        number: true
    };

$('#myForm').validate({
    rules: {
        field_1: ruleSet1,
        field_2: ruleSet1,
        field_3: ruleSet1
    }
});

演示http://jsfiddle.net/rq5ra/4/


选项 2b) 与上述 2a 相关,但取决于您的复杂程度,可以分离出某些组共有的规则,并使用.extend() 以无数种方式重新组合它们.

var ruleSet_default = {
        required: true,
        number: true
    };

var ruleSet1 = {
        max: 99
    };
$.extend(ruleSet1, ruleSet_default); // combines defaults into set 1

var ruleSet2 = {
        min: 3
    };
$.extend(ruleSet2, ruleSet_default); // combines defaults into set 2

var ruleSet3 = { };
$.extend(ruleSet3, ruleSet1, ruleSet2); // combines sets 2 & 1 into set 3.  Defaults are included since they were already combined into sets 1 & 2 previously.

$('#myForm').validate({
    rules: {
        field_1: ruleSet2,
        field_2: ruleSet_default,
        field_3: ruleSet1,
        field_4: ruleSet3
    }
});

最终结果:

  • field_1 是一个不小于 3 的必填数字。
  • field_2 只是一个必填数字。
  • field_3 是不大于 99 的必填数字。
  • field_4 是 3 到 99 之间的必填数字。

演示http://jsfiddle.net/rq5ra/5/

【讨论】:

  • @Sparky 是选项 1a 中仍需要的名称属性吗?
  • @turbo2oh,是的。有了这个插件,每个输入元素必须有一个唯一的name.
【解决方案2】:

你可以使用addClassRules,比如:

jQuery.validator.addClassRules("name", { required: true, minlength: 2 });

【讨论】:

    【解决方案3】:

    jQuery.validator.addClassRules(); 会将验证附加到类,但没有消息选项,它将使用一般错误消息。

    如果你想让它起作用,你应该像这样重构规则

    $.validator.addMethod(
         "newEmail", //name of a virtual validator
         $.validator.methods.email, //use the actual email validator
         "Random message of email"
    );
    
    //Now you can use the addClassRules and give a custom error message as well.
    $.validator.addClassRules(
       "email", //your class name
       { newEmail: true }
     );
    

    【讨论】:

    • 您的回答今天解决了我的问题。对于没有固定数量的元素并且非常依赖于某些因素的情况,此解决方案非常有用
    【解决方案4】:

    替代方法:

    $.validator.addMethod("cMaxlength", function(value, element, param) {
    		
    	return $.validator.methods.maxlength.call(this, value, element, param[1]);
    
    }, '{0}');

    要点:https://gist.github.com/uhtred/833f3b957d61e94fbff6

    $.validator.addClassRules({
        'credit-card': {
        	cMaxlength: [ 'Invalid number.', 19 ]
        }
    });

    【讨论】:

      【解决方案5】:

      $.validator.addMethod("cMaxlength", function(value, element, param) {
      		
      	return $.validator.methods.maxlength.call(this, value, element, param[1]);
      
      }, '{0}');

      【讨论】:

        【解决方案6】:

        我基于 Starx 的回答创建了一个可重复且易于使用的函数,该函数使用默认方法并为特定类创建新的错误消息。考虑到您的特定类将仅用于覆盖消息,一旦您不应该有任何冲突,使用任何现有方法将其用于许多不同的类名。

        var CreateValidation = function(className, customMessage, validationMethod){
          var objectString = '{"'+ className +'": true}',
          validator = $.validator;
        
          validator.addMethod(
            className,
            validator.methods[validationMethod],
            customMessage
          );
          validator.addClassRules(
            className,
            JSON.parse(objectString)
          );
        };
        

        验证类为“validation-class-firstname”的使用示例:

        CreateValidation('validation-class-firstname', 'Please enter first name', 'required');
        

        【讨论】:

          【解决方案7】:

          您可以使用 addClassRules 方法添加类规则:

          例如

          $.validator.addClassRules("your-class", {
            required: true,
            minlength: 2
          });
          

          https://jqueryvalidation.org/jQuery.validator.addClassRules/

          【讨论】:

            【解决方案8】:

            $.validator.addMethod("cMaxlength", function(value, element, param) {
            		
            	return $.validator.methods.maxlength.call(this, value, element, param[1]);
            
            }, '{0}');

            【讨论】:

              【解决方案9】:

              在此之前您必须包含查询文件

              $("#myform_name").validate({
                  onfocusout: function(element) { $(element).valid(); } ,
                  rules:{
                     myfield_name: {
                        required:true
                     },
                     onkeyup: false,
                     messages: {
                        myoffer: "May not be empty"
                     }
                  }
              });
              

              【讨论】:

              • 你的答案是一个精确的副本,一个字一个字的this one。除了是重复的答案之外,它根本不是答案。显然,当 OP 这么说时,jQuery 文件已经包含在内,“jQuery Validation plugin works great”.
              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2016-10-04
              • 1970-01-01
              • 2016-02-07
              • 1970-01-01
              • 2011-10-25
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多