最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin5浏览0评论

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>                          

/

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/gL1k4efa/6/

Share edited May 23, 2017 at 12:31 CommunityBot 11 silver badge asked May 5, 2016 at 11:03 NathanNathan 4994 silver badges16 bronze badges 11
  • share more code details – user5200704 Commented May 5, 2016 at 11:26
  • What else is there you wanted to see? – Nathan 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 – Nathan Commented May 5, 2016 at 11:32
  • jsfiddle/gL1k4efa/6 – Nathan 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 – user3791372 Commented May 9, 2016 at 7:42
 |  Show 6 more ments

3 Answers 3

Reset to default 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./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn./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

发布评论

评论列表(0)

  1. 暂无评论