0

I have an HTML form and I'm using the JQuery Validate plugin to require some form fields to be mandatory. I have a radio button field with 3 options:

Hours Days Unsure

and another field to enter a number that corresponds to the hours or days selections. However if the user selects "Unsure" they are not required to enter a number. I can't work out how to only make the number field mandatory if the user doesn't select "Unsure" (i.e. when they select either "Hours" or "Days"). Here's my HTML at the moment:

<form role="form" action="continue.php" method="post" id="durationForm">

 <tr>
 <td colspan = "3">Please enter the duration?</td>
 </tr>
 <tr>
 <td width="10%"><input type="number" class="form-control" id="duration"  name="durationNumber"               required></td>
 <label for="duration" class="validateError"></label>
 <td width="50%">
 <div class="controls">
 <label class="radio">
 <input type="radio" name="duration" id="duration" value="Hours" required> Hours</label>
 <label class="radio">
 <input type="radio" name="duration" id="duration" value="Days" required> Days</label>
 <label class="radio">
 <input type="radio" name="duration" id="duration" value="Unsure" required> Unsure</label>
 <label for="duration" class="validateError"></label>
 </div>
 </td>
 </tr>
 <button type="submit" class="btn btn-primary">Next</button>
 </form>

Here's the script:

  $(document).ready(function () {
       $("#durationForm").validate({ 
       errorClass: "validateError"
      });
 });

I've setup a jsfiddle that shows this as well.

user982124
  • 4,416
  • 16
  • 65
  • 140

1 Answers1

0

From: https://stackoverflow.com/a/19546185/1477051

jQuery Validate actually directly supports this, using dependency expressions.

All you need to do is change your validate options like this:

$('#myform').validate({
    rules: {
        fieldA: {
           required:'#checkA:checked'
        }
    }
});

That's it!

I've used it on your code here: http://jsfiddle.net/xJBX9/1/

Community
  • 1
  • 1
Sunny R Gupta
  • 5,026
  • 1
  • 31
  • 40