具有多个规则的jQuery表单验证插件 [英] jQuery Form Validation plugin with multiple rules

查看:119
本文介绍了具有多个规则的jQuery表单验证插件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jQueryValidation插件。 问题:我想在一个输入字段中使用多个模式规则。例如:

I'm using the jQueryValidation plugin. Problem: I would like to use multiple pattern rules within for one input field. E.g.:

$("form").validate({
 rules: {
    "email": {
        required: true,
        email: true
    },
    "password": {
        required: true,
        pattern: /^[A-Za-z0-9\w]{4,20}/,
        pattern: /^[\d\w\xC4\xD6\xDC\xE4\xF6\xFC\xDF]*$/
    }
 }
});

会发生什么:插件只测试第二个模式规则。例如。输入类似tst的东西(因为这符合秒模式)虽然它违反了第一个模式规则。

What happens: the plugin tests only the second pattern rule. E.g. entering something like "tst" works (as this fulfils the seconds pattern) although it violates the first pattern rule.

据我了解此插件中规则的逻辑,所有规则都必须返回TRUE才能验证表格。

As far as I understand the logic of rules in this plugin, all rules have to return TRUE in order to validate a form.

推荐答案

你不能使用相同的 key:value 对两次,因为第二个实例将覆盖第一个。

You cannot use the same key:value pair twice since the second instance will override the first.

你有几个选项。


  • 将两个正则表达式组合成一个。将使用一条错误消息声明一种方法。因此,您将创建自己的自定义,而不是使用 additional-methods.js 文件中的模式规则/方法。使用 .addMethod()方法的规则。

  • Combine the two regex expressions into one. One method will be declared with one error message. So instead of using the pattern rule/method from the additional-methods.js file, you will create your own custom rule using the .addMethod() method.

不使用正则表达式模式,而是使用 pattern 规则一次并使用 .addMethod()创建新的第二条规则。

Instead of combining the regex patterns, use the pattern rule once and create a new second rule using .addMethod().

请参阅: http:// jqueryvalidation .org / jQuery.validator.addMethod /

我创建了一个专用于每个正则表达式的自定义方法模式,并给它一个语义相关的名称,类似'电子邮件','电话','字母数字','IP'等。(这也是所有正则表达式评估规则处理相同的方式在这个插件内部。)

I'd create a custom method dedicated to each regex pattern and give it a semantically relevant name, something like 'email', 'phone', 'alphanumeric', 'IP', etc. (This is also the same way all the regex evaluated rules are handled internally by this plugin.)

jQuery.validator.addMethod("foo", function(value, element) {
    return this.optional(element) || /^[A-Za-z0-9\w]{4,20}/.test(value);
}, "Your entered data is not foo");

jQuery.validator.addMethod("bar", function(value, element) {
    return this.optional(element) || /^[\d\w\xC4\xD6\xDC\xE4\xF6\xFC\xDF]*$/.test(value);
}, "Your entered data is not bar");

声明如下......

Declared like this...

"password": {
    required: true,
    foo: true,
    bar: true
}

这篇关于具有多个规则的jQuery表单验证插件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆