Skip to content Skip to sidebar Skip to footer

Javascript Validation For Dynamic Element

How can I validate dynamically created text inputs? I have an 'add more' link that creates new ones, and a link to remove them. Each one has a uniqe ID. Also, at least two text box

Solution 1:

Using the Validation plugin you could add rules dynamically. Here's an example:

<?xml version="1.0"?><!DOCTYPE htmlPUBLIC"-//W3C//DTD XHTML 1.0 Strict//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><htmlxmlns="http://www.w3.org/1999/xhtml"xml:lang="fr"lang="fr"><head><metahttp-equiv="Content-Type"content="text/html; charset=utf-8" /><title>Test</title><scripttype="text/javascript"src="jquery-1.4.1.js"></script><scripttype="text/javascript"src="jquery.validate.js"></script><scripttype="text/javascript">var count = 0;
    $(function() {
        $('form').validate({
            rules: {
                input0: {
                    required: true
                }
            },
            message: {
                input0: {
                    required: 'This field is required'
                }
            }
        });

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

            returnfalse;
        });
    });
    </script></head><body><form><inputtype="text"name="input0"value="" /><inputtype="submit"value="OK" /></form><ahref="#">Add input</a></body></html>

Solution 2:

I wrote a blog post explaining how to dynamically add inputs to a form, and simultaneously add validation rules for the jQuery Validate plugin.

In my example, it was an order form for helmets:

//Each set of helmet inputs gets unique IDsfunctionnewHelmetInputs(i){
var inputSet = ''; 
inputSet += '<label for="helmet'+ i +'color">Helmet '+ i +' Color</label>'
inputSet += '<input id="helmet'+ i +'color" name="helmet['+ i +'][color]"/>'
inputSet += '<label for="helmet'+ i +'size">Helmet '+ i +' Size</label>'
inputSet += '<input id="helmet'+ i +'size" name="helmet['+ i +'][size]"/>'return inputSet;
}

//Actually adding them to the page
$('#addhelmet').click(function(){
var i = nextNumber(); //nextNumber() is a closure - see my blog for detailsvar newInputs = newHelmetInputs(i); //i is used above in IDs
$(this).before(newInputs);
('#helmet' + i + 'size').rules('add', {digits: true}); //matching validation rule
});

The blog post goes into more detail, and also explains how to process this with PHP.

As for the requirement that at least two textboxes must be filled, I wrote a jQuery Validate method for that, and a similar one that says "either fill at least X of the fields in this section, or skip the section entirely."

So, for example, if your form lets people order sandwiches, and each sandwich has an input for bread and filling, you can dynamically add fields for as many sandwiches as they want to order. They don't have to fill in anything for sandwich #2, but if they do, they have to give you both the bread AND the filling type.

Solution 3:

A simple way to do it is to count the number of non-empty textboxes on submit.

 $(function()) {
      $('form').submit( function() {
           if ($(this).find('input:text')
                      .filter( function() { return $(this).val() != ''; }) < 2) {
               ... display validation errors...
               returnfalse;
           }
           returntrue;
      });
 }):

Post a Comment for "Javascript Validation For Dynamic Element"