0

I have array of textbox to collect 5 email address. I have used jQuery validate to validate the form to accept email addresses, unfortunately it's validating the first field only.

Though error message comes up for rest of the fields but it allows the form to submit. I need native solution for this issue.

Here is the code snippet:

$(document).ready(function(){
   $('#myform').validate({
       rules:{
          "foo[]":{
               required:true,
               email:true
                }
       },
       messages:{
          "foo[]":{
               required:"required",
               number:'only numbers!!!'
                }
            }
        });
    });

This is the form:

 <form method="post" action="" id="myform">
        <input type="text" name="foo[]" value="">
        <input type="text" name="foo[]" value="">
        <input type="text" name="foo[]" value="">
        <input type="text" name="foo[]" value="">
        <input type="text" name="foo[]" value="">
        <input type="image" name="bar">
    </form>
Sparky
  • 98,165
  • 25
  • 199
  • 285
Sandeep J Patel
  • 910
  • 9
  • 24
  • 1
    `name` must be unique to the form for the plugin to work correctly. [https://jqueryvalidation.org/reference/#link-markup-recommendations]. Check out this [question](https://stackoverflow.com/questions/8829030/jquery-validation-plugin-adding-rules-that-apply-to-multiple-fields) to add same rules to multiple fields. – n4m31ess_c0d3r Nov 09 '17 at 12:04

1 Answers1

2

Here is the fix.You can use Jquery each function

$(document).ready(function(){
      $('#myform').validate({ // initialize the plugin
          // other options
      });

            $("[name^=foo]").each(function () {
            $(this).rules("add", {
                required: true,
                email:true,
                messages: {
                     required:"required"
                }
            });
        });
    });

And the form should looks like:

    <form method="post" action="" id="myform">
        <input type="text" name="foo[1]">
        <input type="text" name="foo[2]">
        <input type="text" name="foo[3]">
        <input type="text" name="foo[4]">
        <input type="text" name="foo[5]">
    </form>
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
Ganesan Js
  • 162
  • 1
  • 10
  • The most relevant part of this answer is the **unique `name` attribute** on each of the text input fields. – Sparky Nov 09 '17 at 17:20