Jquery validate depend field

cesar picture cesar · Oct 20, 2010 · Viewed 57.3k times · Source

I have 4 fields where the user should enter values in at least one of them. So I am trying to validate that each of these 4 fields will be required just when all of them are empty otherwise it won't be required.

The rule seems to be working for the one field I picked to try first, but the required error remains even after I provide a value.

This is my code:

$("#ProspectDtlFrm").validate({
  rules: { 
    prsptEmail: {
      required: function(element) {
        return (
          $("#prsptHomePhone").val() == '' &&
          $("#prsptBusinessPhone").val() == '' &&
          $("#prsptMobilePhone").val() ==''
        ) 
      }                                         
    }    
  },
  messages: {
    prsptEmail: "Please enter your first name"
  }
}); 

Answer

Darin Dimitrov picture Darin Dimitrov · Oct 20, 2010

You could use depends:

$('#ProspectDtlFrm').validate({ 
    rules: {
        prsptEmail: {
            required: {
                depends: function(element) {
                    return ($('#prsptHomePhone').val() == '' && 
                            $('#prsptBusinessPhone').val() == '' && 
                            $('#prsptMobilePhone').val() == '');
                }
            }
        }    
    }, 
    messages: { 
        prsptEmail: 'Please enter your first name'
    } 
});