Javascript Jquery-在一个大验证器方法中调用多个验证器
我有3个验证程序方法来验证表单字段。对于我必须验证的每个表单字段,我需要一直调用这3个验证器。是否可以编写一个验证程序方法,在内部调用这3个方法并返回相应的错误Javascript Jquery-在一个大验证器方法中调用多个验证器,javascript,jquery,jquery-validate,Javascript,Jquery,Jquery Validate,我有3个验证程序方法来验证表单字段。对于我必须验证的每个表单字段,我需要一直调用这3个验证器。是否可以编写一个验证程序方法,在内部调用这3个方法并返回相应的错误 /* * Do not allow a name to include only underscores. */ jQuery.validator.addMethod('notallunderscores', function(value, element) { value = value.replace(/\_/g,'')
/*
* Do not allow a name to include only underscores.
*/
jQuery.validator.addMethod('notallunderscores', function(value, element)
{
value = value.replace(/\_/g,'');
return this.optional(element) || value.length > 0;
}, "Enter more than only underscore characters.");
/*
* Do not allow a name to include only hyphens.
*/
jQuery.validator.addMethod('notallhyphens', function(value, element)
{
value = value.replace(/\-/g,'');
return this.optional(element) || value.length > 0;
}, "Enter more than only hyphens.");
/*
* Do not allow a name to include leading or trailing spaces.
*/
jQuery.validator.addMethod('notrailingorleadingspaces', function(value, element)
{
return this.optional(element) || ! value.match(/^ .*|.*\ $/g);
}, "Please remove any leading or trailing spaces.");
我正在寻找的验证程序应该如下所示:
/*
* Call each of the above validator methods and return appropriate error.
*/
jQuery.validator.addMethod('validateformfield', function(value, element)
{
//Call the above 3 validator methods
//Return the appropriate error returned by the above validators.
}, "Return the error message from the failed validator.");
不可以,您不能将三个不同的自定义方法组合到一个自定义方法中,同时维护三个不同的错误消息。没有一种方法可以将它们相互嵌套
但是,您可以使用创建“复合规则”并将其分配给
类
然后将类
分配给输入
,您希望在其中应用这些规则
<input type="text" name="foo" class="myCompoundRule ...
您还可以将各种规则组合成“集合”。请参阅下面我的SO答案,了解将多个规则分配给多个字段的其他创造性方法
<input type="text" name="foo" class="myCompoundRule ...
$('#myform').validate({
rules: {
foo: {
notallunderscores: true,
notallhyphens: true,
notrailingorleadingspaces: true
}
}
});