3

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

  • 至少需要一个
  • 如果存在任何字符,则字符长度必须为 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,所以希望有效的解决方案也更有说服力。

4

1 回答 1

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." );
于 2012-04-14T15:51:17.043 回答