jQuery Validate - 只允许两个中的一个

时间:2013-06-12 09:29:54

标签: jquery jquery-validate

需要一些帮助。所以有一个表格,我有两个领域移动和电话。只需要一个。我的下面的代码就是这样,但我想要的是我不希望人们填写这两个。有人可以指导我如何做到这一点。

因此,如果两者都是空显示所需的消息,如果一个是空的,则允许发送表单,(完成)

如果两者都是空的,则不允许发送表单并显示消息。 (需要帮助)

是的,我正在使用jQuery Bassistance Validator

非常感谢提前。

mobile : {
    required: function(element) {  
        if ($("#telephone").val().length > 0) {
            return false;
        }
        else {
            return true;
        }
    }
},                                               
telephone: {
    required: function(element) {
        if ($("#mobile").val().length > 0) {
            return false;
        }
        else {
            return true;
        }
    }
},  
messages: {
    mobile: "Mobile is required",                        
    telephone: "Telephone is required",
},  

4 个答案:

答案 0 :(得分:3)

通过快速阅读文档,看起来验证器的默认方法设计用于对不了解其他字段的字段进行操作。定义自己的东西可能比较简洁:

function XOR_value_validator(value, el, args) {
    var otherValue = $(args[0]).val();
    return (value && !otherValue) || (!value && otherValue);
}

jQuery.validator.addMethod(
    'XOR_with',
    XOR_value_validator,
    jQuery.validator.format('{1}')
);

使用类似的东西:

mobile : {
    XOR_with: [
        '#telephone', // assumed to be a jQuery selector for an element with a value()
        'Please enter either a telephone number or a mobile number.' // error message
    ]
},
telephone: {
    XOR_with: [
        '#mobile', // assumed to be a jQuery selector for an element with a value()
        'Please enter either a telephone number or a mobile number.' // error message
    ]
}

http://jqueryvalidation.org/jQuery.validator.addMethod

这不保修! :P我在这个文本区域中完全没有经过测试(来自文档)。

修改

关于评论:

如果在用户填写表单时不断执行此代码,您可能会在功能上进行相应的启用/禁用表单元素。但是,我建议不要这样做,因为这部分代码应该只关注验证而不是UX。

要扩展两个以上字段的功能(同样,未经测试),您可以执行以下操作:

function one_field_allowed_validator(value, el, args) {
    var otherFields = args[0],
        valuesFound = value ? 1 : 0;

    for (var i = 0, limit = otherFields.length; i < limit; ++i) {
        var val = $(otherFields[i]).val();
        if (val && ++valuesFound === 2) {
            return false;
        }
    }
    return valuesFound !== 0;
}

jQuery.validator.addMethod(
    'Allow_one_with',
    one_field_allowed_validator,
    jQuery.validator.format('{1}')
);

用法:

mobile : {
    Allow_one_with: [
        ['#telephone', '#work'],
        'Please enter a telephone number, a mobile number or a work number.'
    ]
},
telephone: {
    Allow_one_with: [
        ['#mobile', '#work'],
        'Please enter a telephone number, a mobile number or a work number.'
    ]
},
work: {
    Allow_one_with: [
        ['#mobile', '#telephone']
        'Please enter a telephone number, a mobile number or a work number.'
    ]
}

现在感觉非常hacky!对于Allow_one_with组中的每个附加字段,您必须更新所有现有的Allow_one_with验证(包括新字段和可能的新错误消息)。我不愿意将我的方法用于 XOR

答案 1 :(得分:0)

您可以使用已验证项目的数量保留变量:

validatedItems : 0,

mobile : {
    var self = this;
    required: function(element) {  
        if ($("#telephone").val().length > 0) {
            self.validatedItems--;
            return false;
        }
        else {
        self.validatedItems++;
            return true;
        }
    }
},                                               
telephone: {
    var self = this;
    required: function(element) {
        if ($("#mobile").val().length > 0) {
            self.validatedItems--;
             return false;
         }
         else {
            self.validatedItems++;
            return true;
        }
    }
},

然后,您可以在发送表单时检查是否验证了一个或多个项目:

if( validatedItems > 0 ) {
    sendForm();
}

答案 2 :(得分:0)

将所需方法与dependency-espression(jquery选择器)一起使用,这种情况使用:blank伪选择器,它是validate插件的一部分

$(form).validate({
   rules
   {
     mobile:{required: '#telephone:blank'}
     telephone:{required: '#mobile:blank'}
   }
});
来自docs的

- '您的表达式通常会使用选择器过滤器,例如#foo:checked,#foo:filled,#foo:visible。此插件提供custom selectors for that purpose'

修改

抱歉,我没有完全阅读这个问题。最接近您需要的方法是在jQuery validate的additional-methods.js文件中找到的require_from_group方法。您需要进行非常小的调整才能测试您组中的一个经过验证的字段。

例如

<form>
    <input class="productinfo" name="partnumber" />
     <input class="productinfo" name="description" />
     <input type="submit" />
</form>

代码

jQuery.validator.addMethod("require_from_group_exact", function(value, element, options) {
    var validator = this;
    var selector = options[1];
    var validOrNot = $(selector, element.form).filter(function() {
        return validator.elementValue   (this);
    }).length == options[0];

    if(!$(element).data('being_validated')) {
        var fields = $(selector, element.form);
        fields.data('being_validated', true);
        fields.valid();
        fields.data('being_validated', false);
    }
    return validOrNot;
}, jQuery.format("Please fill {0} of these fields."));

$('form').validate({
    rules:{
    partnumber:  {require_from_group_exact: [1,".productinfo"]},
    description: {require_from_group_exact: [1,".productinfo"]}
    }
 });

如果你将它与addtional-methods.js中的原始方法进行比较,你会发现它几乎是一样的。

希望这会有所帮助 - 你需要用'电话'和'手机'替换partnumber和description,你应该设置好。

fiddle here

答案 3 :(得分:0)

此解决方案使用Validation插件中的标准功能。我使用require_from_group规则来确保至少填充了一个,然后我使用maxlength规则禁止一个如果另一个填充。只需确保将phone-group类添加到两个输入字段以支持require_from_group规则。

$("form").validate({
    rules: {
        mobile: {
            require_from_group: [1, ".phone-group"], 
            maxlength: {param: 0, depends: "#telephone:filled"}
        },
        telephone: {
            require_from_group: [1, ".phone-group"], 
            maxlength: {param: 0, depends: "#mobile:filled"}
        }
    },
    messages: {
        mobile: "Please enter either a telephone number or a mobile number.",
        telephone: "Please enter either a telephone number or a mobile number."
    }
});