【问题标题】:Jquery - Calling multiple validators inside one big validator methodJquery - 在一个大型验证器方法中调用多个验证器
【发布时间】:2015-02-10 18:29:24
【问题描述】:

我有 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.");

【问题讨论】:

    标签: javascript jquery jquery-validate


    【解决方案1】:

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


    但是,您可以制定“复合规则”并使用the addClassRules method 将其分配给class

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

    然后您将class 分配给您希望这些规则适用的input...

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-16
      • 2018-09-08
      • 2011-08-04
      • 1970-01-01
      • 2012-11-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多