jQuery 验证插件 - 添加适用于多个字段的规则

发布于 2024-12-26 11:34:21 字数 790 浏览 1 评论 0原文

我正在使用 jQuery 验证 插件:

我有几个字段在一个大的我想要应用相同规则的表单。我已经简化了这个例子的代码。这段代码不起作用,但我想做这样的事情。第二条规则应适用于 first_namelast_name。我想将所有规则封装在此函数中,而不是编辑某些表单元素的类列表以添加所需的类或其他内容。

(同样,我有几组不同的表单字段,它们具有不同的要求,我想将它们分组。为了简单起见,我只将 required: true 放在该元素中)

$('#affiliate_signup').validate(
       {
          rules: 
          {
            email: {
                required: true,
                email: true
            },
            first_name,last_name: {
                required: true
            },
            password: {
                required: true,
                minlength: 4
            }
          }
       });

提前致谢。

I'm using the jQuery Validation plugin:

I have several fields in a large form that I want to apply the same rules to. I've simplified the code for this example. This code doesn't work, but I want to do something like this. The second rule should apply to both first_name and last_name. I want to encapsulate all the rules here in this function and not edit the class lists of some of the form elements to add a required class or whatever.

(Again, I have several different groups of form fields with different requirements that I want to group. I only put required: true in that element for simplicity)

$('#affiliate_signup').validate(
       {
          rules: 
          {
            email: {
                required: true,
                email: true
            },
            first_name,last_name: {
                required: true
            },
            password: {
                required: true,
                minlength: 4
            }
          }
       });

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

终陌 2025-01-02 11:34:21

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

HTML:

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

jQuery:

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

http://jsfiddle.net/9W3F7


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

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

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

http://jsfiddle.net/9W3F7/1


选项 1b) 相关到上面的 1a,但根据您的复杂程度,可以分离出某些组通用的规则并使用 .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

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

最终结果:

  • field_1 将是不小于 3 的必需数字。

  • < code>field_2 将只是一个必需的数字。

  • field_3 将是不大于 99 的必需数字。

http://jsfiddle.net/9W3F7/2


选项 2a) 您可以根据在所需的共同点上规则,然后将这些规则分配给类。使用 addClassRules 方法,我们获取复合规则并将它们转换为类名。

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" />

jQuery:

$('#myform').validate({ // initialize the plugin
    // other options
});

$.validator.addClassRules({
    num: {
        required: true,
        number: true
    }
});

http://jsfiddle.net/9W3F7/4/


选项 2b) 与选项 2a 的主要区别在于,您可以在创建规则后立即调用 rules('add') 方法,将规则分配给动态创建的输入元素。您可以使用class作为选择器,但这不是必需的。如下所示,我们使用通配符选择器而不是 class

.rules() 方法必须在调用 .validate() 之后随时调用。

jQuery:

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

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

http://jsfiddle.net/9W3F7/5/


文档:

For the purposes of my example, this is the base starting code:

HTML:

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

jQuery:

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

http://jsfiddle.net/9W3F7


Option 1a) You can pull out the groups of rules and combine them into common variables.

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

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

http://jsfiddle.net/9W3F7/1


Option 1b) Related to 1a above but depending on your level of complexity, can separate out the rules that are common to certain groups and use .extend() to recombine them in an infinite numbers of ways.

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

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

End Result:

  • field_1 will be a required number no less than 3.

  • field_2 will just be a required number.

  • field_3 will be a required number no greater than 99.

http://jsfiddle.net/9W3F7/2


Option 2a) You can assign classes to your fields based on desired common rules and then assign those rules to the classes. Using the addClassRules method we're taking compound rules and turning them into a class name.

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" />

jQuery:

$('#myform').validate({ // initialize the plugin
    // other options
});

$.validator.addClassRules({
    num: {
        required: true,
        number: true
    }
});

http://jsfiddle.net/9W3F7/4/


Option 2b) The main difference from option 2a is that you can use this to assign rules to dynamically created input elements by calling rules('add') method immediately after you create them. You could use class as the selector, but it's not required. As you can see below, we've used a wildcard selector instead of class.

The .rules() method must be called any time after invoking .validate().

jQuery:

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

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

http://jsfiddle.net/9W3F7/5/


Documentation:

萌逼全场 2025-01-02 11:34:21

您可以通过以下方式使用“getter”语法:

   {
      rules: 
      {
        email: {
            required: true,
            email: true
        },

        first_name: {
            required: true
        },

        get last_name() {return this.first_name},

        password: {
            required: true,
            minlength: 4
        }
      }
   }

You can use the 'getter' syntax in this way:

   {
      rules: 
      {
        email: {
            required: true,
            email: true
        },

        first_name: {
            required: true
        },

        get last_name() {return this.first_name},

        password: {
            required: true,
            minlength: 4
        }
      }
   }
心欲静而疯不止 2025-01-02 11:34:21

如果我理解正确的话,你想将许多规则应用于许多领域,这些规则可能在某些规则上有所不同,但你又懒得在其他领域重复使用相同的规则。
然而,使用 jQuery 验证,一个输入字段上可能有多个规则。这里只需使用数组表示法即可。

要实现您的用例,只需将 data 属性添加到每个输入字段以及您要应用的规则即可。最好的情况是,使用 url 编码的 json 格式,这样每个输入字段只需要一个 data 属性。例如:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>validate test</title>
</head>
<body>
<form id="myForm" name="myForm" method="post" action="www.example.com/my-url">
    <input type="text" name="txt1" data-rules="%7B%22required%22%3Atrue%2C%22minlength%22%3A2%2C%22maxlength%22%3A10%7D" />
    <input type="text" name="txt2" data-rules="%7B%22required%22%3Atrue%2C%22minlength%22%3A2%2C%22maxlength%22%3A10%7D" />
    <input type="number" name="number1" data-rules="%7B%22required%22%3Atrue%2C%22number%22%3Atrue%2C%22min%22%3A1%2C%22max%22%3A999%7D" />
    <input type="email" name="email1" data-rules="%7B%22required%22%3Atrue%2C%22email%22%3Atrue%2C%22minlength%22%3A20%7D" />
    <input type="email" name="email2" data-rules="%7B%22required%22%3Atrue%2C%22email%22%3Atrue%2C%22minlength%22%3A20%7D" />
</form>
<script type="text/javascript">
    var $field = null;
    var rules = {};

    $('#myForm input, #myForm textarea').each(function (index, field) {
        $field = $(field);
        rules[$field.attr('name')] = JSON.parse(decodeURIComponent($field.attr('data-rules')));
    });

    $('#myForm').validate(rules);
</script>
</body>
</html>

其背后的基本技术很简单:

  1. 使用“data-”属性创建字段。
  2. 循环每个输入字段以获取您想要应用的规则。
  3. 将收集的规则应用于表单元素

您还可以通过这种方式使用具有相同验证器的输入组,例如,通过使用它的类和带有规则对象的预定义 JavaScript 变量。我想你已经知道如何以一种优雅的方式变得懒惰了;-)

If I understood you right, you want to apply many rules to many fields, that may differ at some rules, but you are too lazy to repeat yourself with the same rules to other fields.
However, with jQuery validate it's possible to have more than one rule on one input field. Just use the array notation here.

To achieve your use case, just add data attributes to each input field with the rules you want to apply to it. In best case, use an url encoded json format, so that you just need one data attribute per each input field. E. g.:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>validate test</title>
</head>
<body>
<form id="myForm" name="myForm" method="post" action="www.example.com/my-url">
    <input type="text" name="txt1" data-rules="%7B%22required%22%3Atrue%2C%22minlength%22%3A2%2C%22maxlength%22%3A10%7D" />
    <input type="text" name="txt2" data-rules="%7B%22required%22%3Atrue%2C%22minlength%22%3A2%2C%22maxlength%22%3A10%7D" />
    <input type="number" name="number1" data-rules="%7B%22required%22%3Atrue%2C%22number%22%3Atrue%2C%22min%22%3A1%2C%22max%22%3A999%7D" />
    <input type="email" name="email1" data-rules="%7B%22required%22%3Atrue%2C%22email%22%3Atrue%2C%22minlength%22%3A20%7D" />
    <input type="email" name="email2" data-rules="%7B%22required%22%3Atrue%2C%22email%22%3Atrue%2C%22minlength%22%3A20%7D" />
</form>
<script type="text/javascript">
    var $field = null;
    var rules = {};

    $('#myForm input, #myForm textarea').each(function (index, field) {
        $field = $(field);
        rules[$field.attr('name')] = JSON.parse(decodeURIComponent($field.attr('data-rules')));
    });

    $('#myForm').validate(rules);
</script>
</body>
</html>

The basic technology behind that is simple:

  1. Create your fields with the `data-`` attribute.
  2. Loop over each input field to grab the rules that you want to apply on it.
  3. Apply your collected rules to the form element

You could also use input groups with the same validators that way, e. g. by using classes for it and predefined JavaScript variables with the rules object. I think you got the idea on how to get lazy in an elegant way ;-)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文