我们如何按类指定jquery验证插件的规则?

时间:2022-07-04 23:59:25

The jQuery Validation plugin works great and is very easy to use:

jQuery Validation插件运行良好,非常易于使用:

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

Just by setting css classes like "required email", the default message will be displayed.

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

However, I need to customize the messages. The documentation says you can specify rules using a key-value pair for elements and their corresponding messages:

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

$(".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"
     }
   }
})

But, it is not practical to specify a rule for every form element, especially server-generated controls in ASP.NET. Is it possible to specify rules that would apply to ALL elements? Or can I use a class selector somehow?

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

I tried the following, but it didn't work:

我尝试了以下,但它不起作用:

$("#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"
        }
    }
});

That seemed to have a syntax error - the plugin didn't do anything. Then I tried:

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

$("#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"
        }
    }
});

This didn't have any syntax error - the plugin worked, but it ignored the rules/custom messages. Has anyone here used jQuery Validation plugin? If so, how did you apply rules/custom messages to multiple elements?

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

Thanks!

谢谢!

8 个解决方案

#1


69  

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

出于我的例子的目的,这是基本的起始代码:

HTML:

HTML:

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

JS:

JS:

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

DEMO: http://jsfiddle.net/rq5ra/

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


NOTE: No matter which technique below is used to assign rules, it's an absolute requirement of the plugin that every element has a unique name attribute.

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


Option 1a) You can assign classes to your fields based on desired common rules and then assign those rules to the classes. You can also assign custom messages.

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

HTML:

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

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

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

JS:

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"
        }
    });
});

DEMO: http://jsfiddle.net/rq5ra/1/

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

Option 1b) Same as above, but instead of using a class, it matches a common part of the name attribute:

选项1b)与上面相同,但它不是使用类,而是匹配name属性的公共部分:

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

DEMO: http://jsfiddle.net/rq5ra/6/

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


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

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

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

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

DEMO: http://jsfiddle.net/rq5ra/4/

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


Option 2b) Related to 2a 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.

选项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
    }
});

End Result:

最终结果:

  • field_1 will be a required number no less than 3.
  • field_1将是一个不少于3的必填数字。
  • field_2 will just be a required number.
  • field_2只是一个必需的数字。
  • field_3 will be a required number no greater than 99.
  • field_3将是一个不大于99的必需数字。
  • field_4 will be a required number between 3 and 99.
  • field_4将是3到99之间的必需数字。

DEMO: http://jsfiddle.net/rq5ra/5/

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

#2


23  

You could use addClassRules, like:

您可以使用addClassRules,例如:


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

#3


18  

jQuery.validator.addClassRules(); will attach the validation to class, but there is no option for messages, it will use the general error messages.

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

If you want that to work then, you should refactor the rules like this

如果你希望它能够工作,你应该重构这样的规则

$.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


0  

Alternative approach:

替代方法:

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

}, '{0}');

Gist: https://gist.github.com/uhtred/833f3b957d61e94fbff6

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

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

#5


0  

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

}, '{0}');

#6


0  

I've built upon Starx's answer to create a repeatable easy to use function that uses the default methods and creates new error messages for specific classes. considering the fact that your specific class will only be used to override the message once you shouldn't have any conflicts reusing this for many different class names using any existing methods.

我建立在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)
  );
};

Usage Example with validation class being "validation-class-firstname":

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

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

#7


0  

You can add class rules using the addClassRules method:

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

E.g.

例如。

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

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

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

#8


-1  

Before this you have to include Query file

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

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

#1


69  

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

出于我的例子的目的,这是基本的起始代码:

HTML:

HTML:

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

JS:

JS:

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

DEMO: http://jsfiddle.net/rq5ra/

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


NOTE: No matter which technique below is used to assign rules, it's an absolute requirement of the plugin that every element has a unique name attribute.

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


Option 1a) You can assign classes to your fields based on desired common rules and then assign those rules to the classes. You can also assign custom messages.

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

HTML:

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

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

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

JS:

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"
        }
    });
});

DEMO: http://jsfiddle.net/rq5ra/1/

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

Option 1b) Same as above, but instead of using a class, it matches a common part of the name attribute:

选项1b)与上面相同,但它不是使用类,而是匹配name属性的公共部分:

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

DEMO: http://jsfiddle.net/rq5ra/6/

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


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

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

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

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

DEMO: http://jsfiddle.net/rq5ra/4/

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


Option 2b) Related to 2a 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.

选项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
    }
});

End Result:

最终结果:

  • field_1 will be a required number no less than 3.
  • field_1将是一个不少于3的必填数字。
  • field_2 will just be a required number.
  • field_2只是一个必需的数字。
  • field_3 will be a required number no greater than 99.
  • field_3将是一个不大于99的必需数字。
  • field_4 will be a required number between 3 and 99.
  • field_4将是3到99之间的必需数字。

DEMO: http://jsfiddle.net/rq5ra/5/

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

#2


23  

You could use addClassRules, like:

您可以使用addClassRules,例如:


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

#3


18  

jQuery.validator.addClassRules(); will attach the validation to class, but there is no option for messages, it will use the general error messages.

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

If you want that to work then, you should refactor the rules like this

如果你希望它能够工作,你应该重构这样的规则

$.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


0  

Alternative approach:

替代方法:

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

}, '{0}');

Gist: https://gist.github.com/uhtred/833f3b957d61e94fbff6

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

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

#5


0  

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

}, '{0}');

#6


0  

I've built upon Starx's answer to create a repeatable easy to use function that uses the default methods and creates new error messages for specific classes. considering the fact that your specific class will only be used to override the message once you shouldn't have any conflicts reusing this for many different class names using any existing methods.

我建立在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)
  );
};

Usage Example with validation class being "validation-class-firstname":

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

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

#7


0  

You can add class rules using the addClassRules method:

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

E.g.

例如。

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

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

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

#8


-1  

Before this you have to include Query file

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

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