我的手机和家庭电话领域有以下要求:
我在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,所以希望有效的解决方案也更有说服力。
答案 0 :(得分:1)
我没时间测试这个,但也许是这样的:
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." );