代码之家  ›  专栏  ›  技术社区  ›  user755806

JQuery验证插件基于模式的验证?

  •  0
  • user755806  · 技术社区  · 11 年前

    我有一个有5个输入字段的表单,我有下面的验证。我正在使用jquery验证插件。

    <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"></script>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/additional-methods.js"></script>
    

    JQuery代码:

    $("#commentForm").validate({
        rules: {
         cname1: { required : true, minlength: 2 },
         cname2: { required : true, minlength: 2 },
         cname3: { required : true, minlength: 2 },
         cname4: { required : true, minlength: 2 },
         cname5: { required : true, minlength: 2 }
        }
    });
    

    验证工作正常,没有任何问题。我的要求是,正如你所看到的,所有输入名称都以fiwth开头 cname 。这里不是为所有以相同名称开头的字段定义规则 计算机名称 ,我可以根据模式定义规则吗?类似 $('[name^="cname"]') ?

    谢谢

    2 回复  |  直到 11 年前
        1
  •  1
  •   Artek Wisniewski    11 年前
    $("#commentForm").validate();
    $('#commentForm [name^="cname"]').each(function() {
    
     $(this).rules('add', { required : true, minlength: 2 });
    
    });
    

    同时检查 jQuery.validator.addClassRules 用于添加您自己的基于类的规则(如.min-2或smth)

        2
  •  -1
  •   gpolek    11 年前

    试试这个:

    $( "[name^='cname']" ).rules( "add", {
      required: true,
      minlength: 2
    });
    

    更多信息: http://jqueryvalidation.org/rules 。请记住:

    要求验证父窗体,即首先调用$(form).validate()