Jquery validate depend field

Viewed 58448

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"
  }
}); 
5 Answers

'depends' seems like it's not supported any more, and, their docs are not up to date.

So in the scenario where if a 'yes' tick box is checked, validate another field:

rules:{
    'name value of area you want to validate':{
        required: '#tickBoxId:checked'
    }
}

There is a feature just for this scenario: the require_from_group method.

https://jqueryvalidation.org/require_from_group-method

Description: Ensures a given number of fields in a group are complete.

In the options passed to the rule, supply the minimum number of fields within the group that must be complete and a selector to define the group. Then apply this rule to all the fields within the group. The form then cannot be submitted until at least the minimum number have been completed.

Part of the additional-methods.js file

I copied the example from the documentation to this snippet:

$("#myform").validate({
  rules: {
    mobile_phone: {
      require_from_group: [1, ".phone-group"]
    },
    home_phone: {
      require_from_group: [1, ".phone-group"]
    },
    work_phone: {
      require_from_group: [1, ".phone-group"]
    }
  }
});
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/additional-methods.min.js"></script>

<form id="myform">
  <label for="mobile_phone">Mobile phone: </label>
  <input class="phone-group" id="mobile_phone" name="mobile_phone">
  <br/>
  <label for="home_phone">Home phone: </label>
  <input class="phone-group" id="home_phone" name="home_phone">
  <br/>
  <label for="work_phone">Work phone: </label>
  <input class="phone-group" id="work_phone" name="work_phone">
</form>

Related