gpt4 book ai didi

javascript - Jquery - 在一个大验证器方法中调用多个验证器

转载 作者:行者123 更新时间:2023-11-29 19:30:03 24 4
gpt4 key购买 nike

我有 3 个验证器方法来验证表单域。对于我必须验证的每个表单字段,我需要一直调用这 3 个验证器。是否可以编写一个验证器方法,在内部调用这 3 个方法并返回适当的错误?

/*
* 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.");

最佳答案

不,您不能将三种不同的自定义方法组合成一个自定义方法,同时还保留三种不同的错误消息。没有办法将它们相互嵌套。


但是,您可以创建一个“复合规则”并将其分配给一个,使用the addClassRules method .

jQuery.validator.addClassRules("myCompoundRule", {
notallunderscores: true,
notallhyphens: true,
notrailingorleadingspaces: true
});

然后将 class 分配给要应用这些规则的 input...

<input type="text" name="foo" class="myCompoundRule ...

否则,如果您不想使用,那么您必须使用.validate() 方法单独声明自定义规则,我想您已经在做...

$('#myform').validate({
rules: {
foo: {
notallunderscores: true,
notallhyphens: true,
notrailingorleadingspaces: true
}
}
});

您还可以将各种规则组合成“集合”。请参阅下面我的 SO 答案,了解将多个规则分配给多个字段的其他创造性方法。

关于javascript - Jquery - 在一个大验证器方法中调用多个验证器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28439087/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com