[javascript] Validate Dynamically Added Input fields

I have used this jquery validation plugin for the following form.

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>

<script>
    $(document).ready(function(){
        $("#commentForm").validate();
    });

    function addInput() {
        var obj = document.getElementById("list").cloneNode(true);
        document.getElementById('parent').appendChild(obj);
    }
</script>

<form id="commentForm" method="get" action="">
    <p id="parent">
        <input id="list"  class="required" />
    </p>

    <input class="submit" type="submit" value="Submit"/>
    <input type="button" value="add" onClick="addInput()" />
</form>

When the add button is clicked a new input is dynamically added. However when the form is submitted only the first input field is validated. How can i validate dynamically added inputs? Thank you...

This question is related to javascript jquery html jquery-validate

The answer is


In case you have a form you can add a class name as such:

<form id="my-form">
  <input class="js-input" type="text" name="samplename" />
  <input class="js-input" type="text" name="samplename" />
  <input class="submit" type="submit" value="Submit" />
</form>

you can then use the addClassRules method of validator to add your rules like this and this will apply to all the dynamically added inputs:

$(document).ready(function() {
  $.validator.addClassRules('js-input', {
    required: true,
  });
  //validate the form
  $('#my-form').validate();
});

The one mahesh posted is not working because the attribute name is missing:

So instead of

<input id="list" class="required"  />

You can use:

<input id="list" name="list" class="required"  />

Modified version


Try using input arrays:

<form action="try.php" method="post">
    <div id="events_wrapper">
        <div id="sub_events">
            <input type="text" name="firstname[]" />                                       
        </div>
    </div>
    <input type="button" id="add_another_event" name="add_another_event" value="Add Another" />
    <input type="submit" name="submit" value="submit" />
</form>

and add this script and jQuery, using foreach() to retrieve the data being $_POST'ed:

<script>                                                                                    
    $(document).ready(function(){
        $("#add_another_event").click(function(){
        var $address = $('#sub_events');
        var num = $('.clonedAddress').length; // there are 5 children inside each address so the prevCloned address * 5 + original
        var newNum = num + 1;
        var newElem = $address.clone().attr('id', 'address' + newNum).addClass('clonedAddress');

        //set all div id's and the input id's
        newElem.children('div').each (function (i) {
            this.id = 'input' + (newNum*5 + i);
        });

        newElem.find('input').each (function () {
            this.id = this.id + newNum;
            this.name = this.name + newNum;
        });

        if (num > 0) {
            $('.clonedAddress:last').after(newElem);
        } else {
            $address.after(newElem);
        }

        $('#btnDel').removeAttr('disabled');
        });

        $("#remove").click(function(){

        });

    });
</script>

Reset form validation after adding new fields.

function resetFormValidator(formId) {
    $(formId).removeData('validator');
    $(formId).removeData('unobtrusiveValidation');
    $.validator.unobtrusive.parse(formId);
}

In regards to @RitchieD response, here is a jQuery plugin version to make things easier if you are using jQuery.

(function ($) {

    $.fn.initValidation = function () {

        $(this).removeData("validator");
        $(this).removeData("unobtrusiveValidation");
        $.validator.unobtrusive.parse(this);

        return this;
    };

}(jQuery));

This can be used like this:

$("#SomeForm").initValidation();

$('#form-btn').click(function () {
//set global rules & messages array to use in validator
   var rules = {};
   var messages = {};
//get input, select, textarea of form
   $('#formId').find('input, select, textarea').each(function () {
      var name = $(this).attr('name');
      rules[name] = {};
      messages[name] = {};

      rules[name] = {required: true}; // set required true against every name
//apply more rules, you can also apply custom rules & messages
      if (name === "email") {
         rules[name].email = true;
         //messages[name].email = "Please provide valid email";
      }
      else if(name==='url'){
        rules[name].required = false; // url filed is not required
//add other rules & messages
      }
   });
//submit form and use above created global rules & messages array
   $('#formId').submit(function (e) {
            e.preventDefault();
        }).validate({
            rules: rules,
            messages: messages,
            submitHandler: function (form) {
            console.log("validation success");
            }
        });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.validate.js"></script>

<script>
    $(document).ready(function(){
        $("#commentForm").validate();
    });

    function addInput() {

        var indexVal = $("#index").val();
        var index = parseInt(indexVal) + 1
        var obj = '<input id="list'+index+'" name=list['+index+']  class="required" />'
        $("#parent").append(obj);

        $("#list"+index).rules("add", "required");
        $("#index").val(index)
    }
</script>

<form id="commentForm" method="get" action="">
    <input type="hidden" name="index" name="list[1]" id="index" value="1">
    <p id="parent">
        <input id="list1"  class="required" />
    </p>
    <input class="submit" type="submit" value="Submit"/>
    <input type="button" value="add" onClick="addInput()" />
</form>

You need to re-parse the form after adding dynamic content in order to validate the content

$('form').data('validator', null);
$.validator.unobtrusive.parse($('form'));

jquery validation plugin version work fine v1.15.0 but v1.17.0 not work for me.

$(document).find('#add_patient_form').validate({
          ignore: [],
          rules:{
            'email[]':
            {
              required:true,
            },               
          },
          messages:{
            'email[]':
            {
              'required':'Required'
            },            
          },    
        });

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to jquery-validate

Phone Number Validation MVC Jquery Validate custom error message location Jquery validation plugin - TypeError: $(...).validate is not a function JQuery Validate input file type jquery to validate phone number Bootstrap with jQuery Validation Plugin jQuery Validation plugin: validate check box jQuery select box validation Confirm Password with jQuery Validate MVC 4 client side validation not working