JQuery Validate Plugin: both required and minlength depending on another field

I have fields for mobile and home phones with the following requirements:

  • At least one required
  • The length of the character must be 12 if any characters are present (regardless of the other field)

I had good experience with jQuery Validate, but it's hard for me to get what I want here. This is what I have:

    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

It also seems like clumsy Javascript for me, so hopefully a solution that works is also more eloquent.

+3
source share
1 answer

I don't have time to check this out, but maybe something like this:

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." );
+1
source

All Articles