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.

3

2 Answers 2

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.");
    }
  });
Sign up to request clarification or add additional context in comments.

5 Comments

Brilliant. I was wondering if I can add a custom error message.
Excellent. Thanks a lot.
There is one problem. As this is validating on class name so the error messages are adding after the last class name. There are couple of input elements after the first select box and then the second select box comes. So if I leave the first select box empty and validate then the error message appears after the last select box.
It working fine with validating class name but you need to add unique name for each element as in fiddle.
Ahh the id should be unique. Sorry for that. Thanks once again.
0

Try this :

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

Hope it will help

1 Comment

I tried but didn't work. Updated fiddle -- jsfiddle.net/squidraj/afgmqf9g/6

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.