gpt4 book ai didi

jQuery 验证 - 只允许二选一

转载 作者:行者123 更新时间:2023-12-01 01:07:58 24 4
gpt4 key购买 nike

需要一点帮助。所以得到了一张表格,其中有两个字段:手机和电话。只需要一个。我下面的代码就是这样做的,但我想要的是我不希望人们同时填写这两个内容。有人可以指导我如何做到这一点吗?

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

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

顺便说一句,我正在使用 jQuery Bassistance 验证器

提前非常感谢。

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",
},

最佳答案

从文档的快速阅读来看,验证器的默认方法似乎是设计用于对不了解其他字段的字段进行操作的。定义自己的可能会更简洁:

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 我在这个文本区域中编写的它完全未经测试(来自文档)。

编辑:

关于评论:

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

要扩展两个以上字段的功能(同样,未测试),您可以这样做:

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.'
]
}

现在感觉很糟糕!对于Allow_one_with 组中的每个附加字段,您必须更新所有现有的Allow_one_with 验证(以包含新字段和可能的新错误消息)。除了XOR之外,我不愿意使用我的方法。

关于jQuery 验证 - 只允许二选一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17062050/

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