gpt4 book ai didi

jQuery 验证插件 : both required and minlength depending on another field

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

我的移动电话和家庭电话字段具有以下要求:

  • 至少需要一个
  • 如果存在任何字符,字符长度必须为 12(无论其他字段如何)

我在 jQuery Validate 方面获得了很好的体验,但在这里获得我想要的东西很困难。这是我目前拥有的:

    rules:
"contact[mobile]":
required: ->
if $('#contact_home_phone').val().length < 12 and $('#contact_mobile').val().length < 12
return 12
else
return false
minlength: ->
if $('#contact_home_phone').val().length < 12 and $('#contact_mobile').val().length < 12
return 12
else
return false

"contact[home_phone]":
required: ->
if $('#contact_mobile').val().length < 12 and $('#contact_home_phone').val().length < 12
return true
else
return false
minlength: ->
if $('#contact_mobile').val().length < 12 and $('#contact_home_phone').val().length < 12
return 12
else
return false

对我来说,这也感觉像是笨重的 Javascript,所以希望有效的解决方案也更加 Eloquent 。

最佳答案

我没有时间测试这个,但也许是这样的:

var val_phone = function ( value, element, params ) {

var phone_fields = [ 'home_phone', 'mobile' ];

var other_field;

while ( other_field = phone_fields.pop() ) {

other_field = "contact_" + other_field;

if ( element.id != other_field ) {

other_field = $( "#" + other_field )[0];

break;

}
// if

}
// while


return Boolean(

value.length == 12 ||

(

value.length == 0 &&

$( other_field ).val().length == 12

)

);

};


$.validator.addMethod( 'contact_phone', val_phone, "You must supply at least one 12-character phone number." );

关于jQuery 验证插件 : both required and minlength depending on another field,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10154720/

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