3

in my webapp i have the need to allow users to enter unlimited email addresses in a form i have this working nicely its allowing multiple input fields to be added and is validating them perfectly thanks to the below question i found

How to validate array of inputs using validate plugin jquery

i have read the question and made the changes to my code and can confirm in console that its validating each input field and not allowing the form to be submitted

my problem is it only shows the "please enter your email" for one of the input fields. for example if i had 2 fields and enter an email in the first when i submit the form the "please enter your email" for the second input shows under the first input field

what possible methods are there to make it show for all

this is my JS so far

    var validator = $(".webapp_auth_login_validation").validate({
        rules: {"email[]": "required"},
        messages: {"email[]": "Please enter you email"}
    }); 

$('.webapp_js_cu_email_new').click(function(){
 $('.webapp_js_cu_email_container').append('<div class="col-md-4 form-group"><label>Additional Email: <span class="text-danger">*</span></label><a href="javascript:void(0);" class="webapp_js_cu_email_remove" title="Remove field"> Remove </a><input type="text" name="email[]" class="form-control required"></div>');
});
$('.webapp_js_cu_email_container').on('click', '.webapp_js_cu_email_remove', function(e){
    e.preventDefault();
    $(this).parent('div').remove();
});

this is the html on the page

<div class="row webapp_js_cu_email_container">
<div class="col-md-4 form-group">                                   
        <label>Email Address:  <span class="text-danger">*</span></label> <a href="javascript:void(0);" class="webapp_js_cu_email_new" > Add </a>
        <input type="text" name="email[]" class="form-control required">                                                                
</div>                          

http://jsfiddle.net/gL1k4efa/6/

11
  • share more code details Commented May 5, 2016 at 11:26
  • What else is there you wanted to see? Commented May 5, 2016 at 11:27
  • The code above is everything apart from including the jquery and validate js file. The code above works but only shows error messages for the first field I will try make a fiddle Commented May 5, 2016 at 11:32
  • jsfiddle.net/gL1k4efa/6 Commented May 5, 2016 at 11:52
  • if it's blank, treat it as the user not wanting to send an email for that text box. it's a usability issue and they may not want / know to delete spare text boxes Commented May 9, 2016 at 7:42

3 Answers 3

3
+50

Here is a workaround to your issue.

Explanation The var validator = ... is used to provide a template to the inputs with email[] names.

They are then selected with their email-input class and provided rules with an email type and required callbacks in the createValidation() function - and a custom error message.

The function is called a first time and whenever you add an email input to the form.

var emailCounter = 1;

var validator = $(".webapp_auth_login_validation").validate({
  rules: {
    "email[]": "required"
  },
  messages: {
    "email[]": "Please enter you email"
  }
});

var createValidation = function() {
  $(".email-input").each(function() {
    $(this).rules('remove');
    $(this).rules('add', {
      email: true,
      required: true,
      messages: {
        email: "Not a valid email.",
        required: "Please enter an email adress."
      }
    });
  });
}

$('.webapp_js_cu_email_new').click(function() {
  $('.webapp_js_cu_email_container').append('<div class="col-md-4 form-group"><label>Additional Email: <span class="text-danger">*</span></label><a href="javascript:void(0);" class="webapp_js_cu_email_remove" title="Remove field"> Remove </a><input id="email[' + (emailCounter) + ']" type="text" name="email[' + (emailCounter) + ']" class="form-control required email-input"></div>');

  // Increment input counter
  ++emailCounter;

  // Create validation
  createValidation();
});

$('.webapp_js_cu_email_container').on('click', '.webapp_js_cu_email_remove', function(e) {
  e.preventDefault();
  $(this).parent('div').remove();
});

// Kick validation
$(document).ready(function() {
  createValidation();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<form class="webapp_auth_login_validation">
  <div class="row webapp_js_cu_email_container">
    <div class="col-md-4 form-group">
      <label>Email Address: <span class="text-danger">*</span>
      </label> <a href="javascript:void(0);" class="webapp_js_cu_email_new"> Add </a>
      <input type="text" name="email[0]" class="form-control required email-input">
    </div>
  </div>
  <input type="submit">
</form>

Sign up to request clarification or add additional context in comments.

2 Comments

this actually makes sense however when i run the snippet code it only shows this field is required not "Please enter you email" for all the email fields
No worries one thing I never thought about is what happens when the input field is removed will the validation fail because the input field no longer exists jsfiddle.net/gL1k4efa/63 this seems to work using classes but I have to define the message twice I like the idea of a function to define once and call it twice
1

Your JS code is right, the problem is with your HTML code. You said have a list of emails, then you need and array, but you have to set indexes to that array or the DOM wont be well formed and the validator will fail.

Try to set and index for each input field.

<div class="col-md-4 form-group">                                   
    <label>Email Address:  <span class="text-danger">*</span></label> <a href="javascript:void(0);" class="webapp_js_cu_email_new" > Add </a>
    <input type="text" name="email[0]" class="form-control required">                                                                
</div> 

And here adding the right index:

$('.webapp_js_cu_email_new').click(function(){
 $('.webapp_js_cu_email_container').append('<div class="col-md-4 form-group"><label>Additional Email: <span class="text-danger">*</span></label><a href="javascript:void(0);" class="webapp_js_cu_email_remove" title="Remove field"> Remove </a><input type="text" name="email[+obtainIndex()+]" class="form-control required"></div>');
});

14 Comments

only the first input field is provided a static number the rest are provided by the jquery
@Nathan then in the JS code you have to set the right index position in the emails array. You should create a function to know the index value and build the input with email[index] correctly. And will works :)
im not sure what you mean by this
@Nathan you only need to be sure that all yours inputs have the attribute "name" with a valid array index position. Here an example, with right indexes jsfiddle.net/hudkkkrz
in the fiddle you provided it only shows the message for the first field none of the others
|
1

You can try below code it validate each field for required validation and also for valid email address check for each field and in this what i did in each element add index using count variable and i have create one function which add validation rules for email and required filed both after every time add new filed. function name for that is callToEnhanceValidate try below code it will solve your problem for both required and valid email address validation also.

    <form class="webapp_auth_login_validation">

    <div class="row webapp_js_cu_email_container">
    <div class="col-md-4 form-group">                                   
            <label>Email Address:  <span class="text-danger">*</span></label> <a href="javascript:void(0);" class="webapp_js_cu_email_new" > Add </a>
            <input type="text" name="email[]" class="form-control required emailValidate">                                                                
    </div>
    </div>           
    <input type="submit">
    </form>



    <script type= text/javascript>
        var count = 1; 
             var validator = $(".webapp_auth_login_validation").validate({
                rules: {"email[]": "required"},
                messages: {"email[]": "Please enter you email"}
            }); 

            var callToEnhanceValidate=function(){
                $(".emailValidate").each(function(){
                    $(this).rules('remove');
                    $(this).rules('add', {
                        required: true,
                        email : true,
                        minlength:2,
 messages: {
                required: "Please enter you email"
            },
                    });
                })
            }
        $('.webapp_js_cu_email_new').click(function(){
            count++;
         $('.webapp_js_cu_email_container').append('<div class="col-md-4 form-group"><label>Additional Email: <span class="text-danger">*</span></label><a href="javascript:void(0);" class="webapp_js_cu_email_remove" title="Remove field"> Remove </a><input type="text" name="email['+count+']" class="form-control required emailValidate"></div>');
        callToEnhanceValidate();
        });

        $('.webapp_js_cu_email_container').on('click', '.webapp_js_cu_email_remove', function(e){
            e.preventDefault();
            $(this).parent('div').remove();
        });
    </script>

in this i have also added new class "emailValidate" in each dynamic generated filed and also for first field so now this code validate for both required and email validation both validation you can also try below fiddle link working code

fiddle link for working demo of required and email validate both validation

6 Comments

when trying this only the first input field shows Please enter you email i need all of them to
Have you tryed in above fiddle link looked in that is shows message for other filed also "Please enter a valid email address." if you try to enter simple text it will shows you message for valid email address also.
[img]i.imgur.com/izxJeas.png[/img] - thats not what i see - see the first field shows please enter your email
so what you want means in each filed you want to display same message which shows in first field can you please explain more so i can help you more.
for every input field added to the page via the code above i wish for it to show "please enter your email" if it doesn't have any text in it when the form is submitted - at the current stage it only shows on the first field and then display "this field is required" for the rest
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.