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/

Community
  • 1
  • 1
Nathan
  • 509
  • 4
  • 16
  • share more code details – user5200704 May 05 '16 at 11:26
  • What else is there you wanted to see? – Nathan May 05 '16 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 – Nathan May 05 '16 at 11:32
  • http://jsfiddle.net/gL1k4efa/6/ – Nathan May 05 '16 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 – user3791372 May 09 '16 at 07:42
  • its validating correctly however the validation error message is not showing in the correct spot under the email that failed validation it always displays under the first. if i have 3 input fields and the 3rd has no data in it the validation will fail for the 3rd input field but show under the first – Nathan May 09 '16 at 07:46
  • Oh, I've had this problem before with other means. It looks like you're not using an id - something like someemail_1, someemail_2 etc, so it can be targetted. Failing that, the index of the failed input or a name etc – user3791372 May 09 '16 at 07:54
  • i have found this jsfiddle http://jsfiddle.net/ThE5K/6/ like you were saying with the ID's however i cannot apply a custom error message this dynamically as the id will always be changing see (messages: {"email[]": "Please enter you email"}) above – Nathan May 09 '16 at 07:57
  • add a data-someindexname="0", data-someindexname="1"? – user3791372 May 09 '16 at 08:06
  • where do i add the above lines to – Nathan May 09 '16 at 08:09
  • @Nathan your problem is solved or not i think last i sent you fiddle link it is working as you want i think you are using that same fiddle so you got your solution or not – Denis Bhojvani May 11 '16 at 04:30

3 Answers3

3

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>
PinkTurtle
  • 6,942
  • 3
  • 25
  • 44
  • 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 – Nathan May 09 '16 at 09:11
  • 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 http://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 – Nathan May 09 '16 at 11:34
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>');
});
cralfaro
  • 5,822
  • 3
  • 20
  • 30
  • only the first input field is provided a static number the rest are provided by the jquery – Nathan May 09 '16 at 09:09
  • @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 :) – cralfaro May 09 '16 at 09:14
  • im not sure what you mean by this – Nathan May 09 '16 at 10:06
  • @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 http://jsfiddle.net/hudkkkrz/ – cralfaro May 09 '16 at 10:09
  • in the fiddle you provided it only shows the message for the first field none of the others – Nathan May 09 '16 at 10:10
  • i tried the new js fiddle however it shows this field is required not "Please enter you email" for every field – Nathan May 09 '16 at 10:19
  • i have created this fiddle and added indexes as you said however now it shows this field is required for all as the email[] has numbers in it how can i validate that dynamically http://jsfiddle.net/rzv280r8/1/ – Nathan May 09 '16 at 10:21
  • @Nathan what do you mean with validate dynamically? what validations you want for each field? required plus valid email? – cralfaro May 09 '16 at 10:37
  • for now i wish to have every dynamic input field added to the page show the custom message "please enter your email" – Nathan May 09 '16 at 10:38
  • that is exactly what im chasing however on adding another completely different input field say a username field if its not specified it just shows "please enter your email" this is not what im chasing anything with the array email[] should show the "please enter your email" anything thats not defined for example a new input field should show the default "this field is required" with the above fiddle it will show "please enter your email" – Nathan May 09 '16 at 10:53
  • i far prefer the function idea like this example http://jsfiddle.net/rzv280r8/4/ i just need it to pass the number specified to createValidation(); to be imputed into the rules and i think that will be what im after – Nathan May 09 '16 at 10:55
  • @Nathan with that example if you click on add several times, the messages are wrong, i would go for this approach http://jsfiddle.net/ss870363/ create rules for the fields with a specific class, i did here some examples with custom messages. Better use class validations from the plugin than create yourself, and email, number, required,...all those validations are already implemented for the plugin you are using, so lets use them ;) – cralfaro May 09 '16 at 11:03
  • the messages are wrong because a static number is assigned in the function createValidation(); instead of numberIncr - im going to test a few things with the aproach you just provided – Nathan May 09 '16 at 11:07
  • after testing http://jsfiddle.net/ss870363/ this stops validating the additional email fields however as @Dinesh Bhojvani provided this fiddle http://jsfiddle.net/gL1k4efa/63/ this seems to work when adding extra fields by removing the class and creating extra classes so i think you have pointed me in the direction – Nathan May 09 '16 at 11:21
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

Denis Bhojvani
  • 817
  • 1
  • 9
  • 18
  • when trying this only the first input field shows Please enter you email i need all of them to – Nathan May 09 '16 at 10:06
  • 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. – Denis Bhojvani May 09 '16 at 10:29
  • [img]http://i.imgur.com/izxJeas.png[/img] - thats not what i see - see the first field shows please enter your email – Nathan May 09 '16 at 10:33
  • 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. – Denis Bhojvani May 09 '16 at 10:41
  • 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 – Nathan May 09 '16 at 10:44
  • Please check this fiddle link i hope this is exactly what you want http://jsfiddle.net/gL1k4efa/63/ hope this is helpful for you – Denis Bhojvani May 09 '16 at 11:10