1

I am trying to validate an array using jQuery Validate plugin. The array has a numeric key and the key number is not sequential. That means, it could be

cause[0] or cause[2] or cause[7]

Html code

<form id="myform" action="submit.php">
  <select name="cause[0]" id="cause" class="cause">
    <option value="">Cause to Support</option>
    <option value="993">Medical</option>
    <option value="355">Children</option>
  </select>
  <select name="cause[2]" id="cause" class="cause">
    <option value="">Cause to Support</option>
    <option value="993">Medical</option>
    <option value="355">Children</option>
  </select>
  <input type="submit" name="submit" value="submit" />
</form>

Demo -- https://jsfiddle.net/squidraj/afgmqf9g/3/

It's not validating and submitting the form to submit.php file. In firebug error console there is no error as well.

Any help is highly appreciated.

Prithviraj Mitra
  • 11,002
  • 13
  • 58
  • 99

2 Answers2

1

Try this Working Fiddle

<form id="myform" action="submit.php">
  <select name="cause[0]" id="cause" class="cause">
    <option value="">Cause to Support</option>
    <option value="993">Medical</option>
    <option value="355">Children</option>
  </select>
  <select name="cause[1]" id="cause1" class="cause">
    <option value="">Cause to Support</option>
    <option value="993">Medical</option>
    <option value="355">Children</option>
  </select>
  <input type="submit" name="submit" value="submit" id="btnSubmit" />
</form>

JQuery Code:

$("#myform").validate();
  $(".cause").each(function () {
      $(this).rules("add", {
          required: true,
          messages: {
            required: "Custom Message for required"
          }
      });
  });

  $("#btnSubmit").click(function(e){    
    var isValid= $("#myform").valid();  
    if(isValid==false){
    e.preventDefault();
    }
    else{
        alert("Validate Successful.");
    }
  });
Bharatsing Parmar
  • 2,435
  • 1
  • 9
  • 18
0

Try this :

$("#myform").validate();
$(".cause").each(function (item) {
    $(this).rules("add", {
        required: true
    });
});

Hope it will help

Sagar Jajoriya
  • 2,377
  • 1
  • 9
  • 17