简体   繁体   中英

validate array of inputs using validate plugin jquery - show errors for each input

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/

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> 

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>');
});

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM