Monday, December 30, 2013

Javascript validation for dynamic element

Many time in web-application we come across the functionality to build - adding dynamic form elements and validating them. its pretty simple with .rules() and validate()

 var newElement = $('<input type="text" name="input' + count + '" value="" />');
            newElement.rules('add', {
                required: true,
                messages: {
                    required: 'This field is required'

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

<script type="text/javascript">
   $(document).ready(function() {
        var numberIncr = 1; // used to increment the name for the inputs

        function addInput() {
            $('#inputs').append($('<input class="comment" name="name'+numberIncr+'" />'));

        $('form.commentForm').on('submit', function(event) {

            // adding rules for inputs with class 'comment'
            $('input.comment').each(function() {
                        required: true

            // prevent default submit action         

            // test if form is valid 
            if($('form.commentForm').validate().form()) {
            } else {
                console.log("does not validate");

        // set handler for addInput button click
        $("#addInput").on('click', addInput);

        // initialize the validator



Know more about JAVASCRIPT, JQUERY, Form Validation, Validate
Hope you have enjoyed the post let us know your views.



  1. I have many times to search the blog for getting this programming segment to make the validation.But this blog only have the exact javascript validation coding.Its really great job.
    Web Development Company | Web Development Companies

  2. Your blog article is very intersting and fanstic,at the same time the blog theme is unique and perfect,great job. Web Design Company Bangalore

  3. for me it's working. Hi, I'm here to recommend WorkingFreelancer if you are interested and can check.
    if you need to hire, for me it's working


Any Questions or Suggestions ?


Professional & Experienced Freelance Developer From India, Technologist, Software Engineer, internet marketer and Open Sources Developer with experience in Finance, Telecoms and the Media. Contact Me for freelancing projects.

Enter your email address:

Delivered by FeedBurner

PHP Freelancer India - Google+