user2191829
user2191829

Reputation: 51

Validating dynamically created content with jQuery Validate plugin

I know that several people have probably asked this same question, but I am having a hard time finding a solution that will work with what I have. I have form that people can add as many lines (that have 4 input boxes per line) as necessary then delete them if they are not used. I am using the .append() jquery function to add the lines and have it working.

I am having a hard time figuring out how to validate the new input boxes. Does any one have a good solution for what I am trying to do? Here is a link to my code:

$(document).ready(function () {

var count = 1;
$('p#add_field').click(function () {

    count += 1;

    $('table#entries').append(
        '<tr>' +
        '<td><input id="cl_' + count + '" name="cl[]' + '" type="text" /></td>' +
        '<td><input id="num_' + count + '" name="num[]' + '" type="text" size="5"/></td>' +
        '<td><input id="description_' + count + '" name="description[]' + '" type="text" size="86"/></td>' +
        '<td><span class="delete">Remove</span></td></tr>');

    $(".delete").click(function () {
        $(this).closest('tr').remove();
    });

});





    // 1. prepare the validation rules and messages.
    var rules = {

        email: {
            required: true,
            email: true
        },
        lname: "required",
        fname: "required",
        city: "required",
        address: "required",
        'cl[]': "required",
        'num[]': "required",
        'description[]': "required",
        age: {
            required: true,
            number: true,
            maxlength: 3
        },
        phone: {
            required: true,
            phoneUS: true
        }



    }; // end var rules


    // 2. Initiate the validator
    var validator
        = new jQueryValidatorWrapper("FormToValidate",
            rules);

    // 3. Set the click event to do the validation
    $("#btnValidate").click(function () {
        if (!validator.validate())
            return;

        alert("Validation Success!");
    });
});

http://jsfiddle.net/9k7ph/4/

Upvotes: 3

Views: 5243

Answers (1)

Sparky
Sparky

Reputation: 98758

1) You are calling .validate() inside your click handler so it's not properly initialized on your form. You would only call it once on DOM ready to initialize the plugin on your form.

2) You do not need to put the submit button inside a click handler either. The jQuery Validate plugin already properly captures the click event.

3) Your dynamically created fields MUST have unique name attributes or the plugin will fail.

4) You must dynamically add the rules to the newly created fields as you create them. Calling .validate() is not the way to do this... new rules/options are ignored after initialization. You can use a built-in method like rules('add'), or even easier, add class="required" to the new input fields and this rule will be picked up automatically.

I scrapped your fiddle and started from scratch... basic validation is working, now you can layer your other plugins back into it.

DEMO: http://jsfiddle.net/X5EvD/

$(document).ready(function () {

    $("#FormToValidate").validate({
        rules: {
            email: {
                required: true,
                email: true
            },
            lname: "required",
            fname: "required",
            city: "required",
            address: "required",
                'cl[]': "required",
                'num[]': "required",
                'description[]': "required",
            age: {
                required: true,
                number: true,
                maxlength: 3
            },
            phone: {
                required: true,
                phoneUS: true
            }
        },
        submitHandler: function (form) {
            alert("Validation Success!");
            return false; // if you need to block normal submit because you used ajax
        }
    });

    var count = 1;
    $('p#add_field').click(function () {

        count += 1;

        $('table#entries').append(
            '<tr>' +
            '<td><input id="cl_' + count + '" name="cl[' + count + ']' + '" type="text" class="required"/></td>' +
            '<td><input id="num_' + count + '" name="num[' + count + ']' + '" type="text" size="5" class="required"/></td>' +
            '<td><input id="description_' + count + '" name="description[' + count + ']' + '" type="text" size="86" class="required"/></td>' +
            '<td><span class="delete">Remove</span></td></tr>');


        $(".delete").click(function () {
            $(this).closest('tr').remove();
        });

    });

});

Upvotes: 3

Related Questions