0
votes

here i am giving my html. i have a dropdown which showing few product info and showing hobbies by checkbox. i want if user select product iPod then validation will not fire for hobbies checkboxes other wise fire. how to perform this kind of conditional validation by jquery validate plugin adding jquery rules.

<form name="TestVal" method="post" action="/" novalidate="novalidate">
    <div class="form-horizontal">
        <h4>DateValTest</h4>
        <hr>

        <div class="form-group">
            <label style="padding-top: 0px;" for="Products" class="control-label col-md-2">Products</label>
            <div class="col-md-10">
                <select name="SelectedProductId" id="SelectedProductId" data-val-required="Select any Product" data-val-number="The field SelectedProductId must be a number." data-val="true">
                    <option value="">-- Select Product--</option>
                    <option value="1">IPhone</option>
                    <option value="2">MacBook Pro</option>
                    <option value="3">iPod</option>
                </select>
                <span data-valmsg-replace="true" data-valmsg-for="SelectedProductId" class="field-validation-valid text-danger"></span>
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10 input-validation-error">
                <b>Hobbies</b><br>
                <input type="checkbox" value="true" name="Hobbies[0].IsSelected" id="Hobbies" data-val-required="The IsSelected field is required." data-val="true" class="hobbycls"><input type="hidden" value="false" name="Hobbies[0].IsSelected">
                &nbsp; 
                <label for="Hobbies_0__IsSelected">Reading</label>
                &nbsp;
                <input type="hidden" value="Reading" name="Hobbies[0].Name" id="Hobbies_0__Name"><input type="checkbox" value="true" name="Hobbies[1].IsSelected" id="Hobbies" data-val-required="The IsSelected field is required." data-val="true" class="hobbycls"><input type="hidden" value="false" name="Hobbies[1].IsSelected">
                &nbsp; 
                <label for="Hobbies_1__IsSelected">Sports</label>
                &nbsp;
                <input type="hidden" value="Sports" name="Hobbies[1].Name" id="Hobbies_1__Name"><input type="checkbox" value="true" name="Hobbies[2].IsSelected" id="Hobbies" data-val-required="The IsSelected field is required." data-val="true" class="hobbycls"><input type="hidden" value="false" name="Hobbies[2].IsSelected">
                &nbsp; 
                <label for="Hobbies_2__IsSelected">Movies</label>
                &nbsp;
                <input type="hidden" value="Movies" name="Hobbies[2].Name" id="Hobbies_2__Name">
            </div>

        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" class="btn btn-default" value="Submit">
            </div>
        </div>
    </div>
</form>

Right now i am doing client side validation by this way

<script type="text/javascript">
    var declarationsError = $('#Hobbies-error');
    $('form').submit(function () {
        if ($("#SelectedProductId option:selected").text() != 'iPod') {
            if ($(".hobbycls:checkbox:checked").length <= 0) {
                declarationsError.empty();
                declarationsError.append("<span>Select Any Hobbie's checkbox</span>");
                declarationsError.show();
                return false;
            } else {
                declarationsError.empty();
                declarationsError.hide();
            }
        }

        declarationsError.hide();
        return true;
    });

    $('.hobbycls').change(function () {
        if ($(this).is(':checked')) {
            declarationsError.empty();
            declarationsError.hide(); // hide error message
        }
    });
</script>

the above script is working fine but i want to do the same using jquery validate plugin adding rules.

so please guide me what jquery validate code i need to write to perform the same. show me how to do this kind of conditional validation by adding jquery rules. thanks

1

1 Answers

0
votes

You have some errors in the produced HTML:

  1. same ID for different elements (i.e.: Hobbies)
  2. labels linked to no element: i.e.: label for="Products"

You may use the jQuery validator to add a new rule to repeat exactly what you do in your two jQuery functions:

  1. $('form').submit(function () {
  2. $('.hobbycls').change(function () {

You forgot to give the Hobbies-error element, so I used a div.

In the following the snippet:

var validator;

// a new rule is required to test if iPod is selected and checkboxes are...
$.validator.addMethod('checkboxMaxIfiPodNotSelected', function (value, elem, param) {
  var selectedOptionVal = $(param.selEleiSiPod).val().trim();
  var selectedOptionText = $(param.selEleiSiPod).text().trim();
  if (selectedOptionText != 'iPod') {
    if (selectedOptionVal.length > 0) {
      if ($(':checkbox.' + elem.classList[0] + ":checked").length <= param.max) {
        $('#Hobbies-error').empty().append("<span>Select Any Hobbie's checkbox</span>").show();
        return false;
      }
    } else {
      $('#Hobbies-error').empty().append("<span>Select a Product</span>").show();
      return false;
    }
  }
  $('#Hobbies-error').empty().hide();
  return true;
});

$(function () {
  // build the dynamic rules....
  var myRules = {};
  var myMessages = {};
  $(':checkbox.hobbycls').each(function (index, element) {
    myRules[element.name] = {
      checkboxMaxIfiPodNotSelected: {
        max: 0,
        selEleiSiPod: '#SelectedProductId option:selected'
      }
    };
    myMessages[element.name] = {
      checkboxMaxIfiPodNotSelected: function(params, element) {
        // it's not usefull to return a true error message because I used a div
        // but this is up to you how to manage and place the errors
        return '';
      }
    };
  });

  // use the rules and messages with validator...
  validator = $('form').validate({
    rules: myRules,
    messages: myMessages,
    submitHandler: function (form) { // for demo
      alert('valid form submitted'); // for demo
      return false; // for demo
    }
  });
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-1.12.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.15.0/jquery.validate.min.js"></script>


<form name="TestVal" method="post" action="/" novalidate="novalidate">
    <div class="form-horizontal">
        <h4>DateValTest</h4>
        <hr>

        <div class="form-group">
            <label style="padding-top: 0px;" for="SelectedProductId" class="control-label col-md-2">Products</label>

            <div class="col-md-10">
                <select name="SelectedProductId" id="SelectedProductId"
                        data-val-required="Select any Product"
                        data-val-number="The field SelectedProductId must be a number." data-val="true">
                    <option value="">-- Select Product--</option>
                    <option value="1">IPhone</option>
                    <option value="2">MacBook Pro</option>
                    <option value="3">iPod</option>
                </select>
                <span data-valmsg-replace="true" data-valmsg-for="SelectedProductId"
                      class="field-validation-valid text-danger"></span>
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10 input-validation-error">
                <b>Hobbies</b><br>
                <input type="checkbox" value="true" name="Hobbies[0].IsSelected" id="Hobbies"
                       data-val-required="The IsSelected field is required." data-val="true" class="hobbycls"><input
                    type="hidden" value="false" name="Hobbies[0].IsSelected">
                &nbsp;
                <label for="Hobbies_0__Name">Reading</label>
                &nbsp;
                <input type="hidden" value="Reading" name="Hobbies[0].Name" id="Hobbies_0__Name">
                <input type="checkbox" value="true" name="Hobbies[1].IsSelected" id="Hobbies1"
                       data-val-required="The IsSelected field is required."
                       data-val="true" class="hobbycls">
                <input type="hidden" value="false" name="Hobbies[1].IsSelected">
                &nbsp;
                <label for="Hobbies_1__Name">Sports</label>
                &nbsp;
                <input type="hidden" value="Sports" name="Hobbies[1].Name" id="Hobbies_1__Name">
                <input type="checkbox" value="true" name="Hobbies[2].IsSelected" id="Hobbies2"
                       data-val-required="The IsSelected field is required."
                       data-val="true" class="hobbycls">
                <input type="hidden" value="false" name="Hobbies[2].IsSelected">
                &nbsp;
                <label for="Hobbies_2__Name">Movies</label>
                &nbsp;
                <input type="hidden" value="Movies" name="Hobbies[2].Name" id="Hobbies_2__Name">
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" class="btn btn-default" value="Submit">
            </div>
        </div>
    </div>
    <div id="Hobbies-error" class="help-block with-errors"></div>
</form>