3

When using the jQuery validation plugin, how do I validate a form that is generated using ajax?

I mean to ask, the form does not initially appear on the page when the page loads, but is added to the page using ajax.

I'm following the examples on bassistance.de/jquery-plugins/jquery-plugin-validation/, but it seems that the validation plugin will not validate the form. Otherwise, it works fine. Is there a way to do this. Just like jquery uses live(), is there something I can use to make the plugin work in this scenario?

I'm doing things this way:

$("#thisForm").validate({

    rules: {

    },

    messages: {

    },

    submitHandler: function() {
    $.ajax({
            type: "POST",
             url: "/",
            data: $('#thisForm').serialize(),
        dataType: "json",
           cache: false,

        beforeSend: function(html) {

        },

    success: function(signInData) {


        },

        });
    }
});
3
  • 2
    Note that live() is deprecated since 1.7. When using on(), the method will work for current and newly created elements, so it should work for you Commented Sep 7, 2013 at 23:27
  • AFAIK, there is no api in validation plugin to do this, but you can call the validate method to add validation to your form, as soon you add it to the dom after the ajax call Commented Sep 7, 2013 at 23:28
  • So then please show the code that dynamically creates the form. Commented Sep 8, 2013 at 13:43

4 Answers 4

3

Quote OP:

"... the form does not initially appear on the page when the page loads, but is added to the page using ajax. ... like jquery uses live(), is there something I can use to make the plugin work in this scenario?"

There is no method available to delegate binding the jQuery Validate plugin to a form that has not yet been constructed.

Since .validate() is the initialization method for the plugin, you simply need to call it immediately after you dynamically create this form.

However, you have not shown the code that creates the form, so this example assumes you create the form by clicking something. Adjust this as needed... just keep in mind that you need to make sure the ajax is complete (the new form exists) before calling .validate() to initialize the plugin.

$(document).ready(function() {  // ensure the DOM is ready

    $('#something').on('click', function() { // clicking something to create the form

        $.ajax({  // your ajax code to create the form
            // your ajax options,
            complete: function() { // fires after the ajax is fully complete
                $("#thisForm").validate({ // initialize the plugin on the new form
                    // options & rules
                });
            }
        });

    });

});

complete: - A function to be called when the request finishes (after success and error callbacks are executed).

See: http://api.jquery.com/jQuery.ajax/

Sign up to request clarification or add additional context in comments.

Comments

0

Try adding DOM delegation with .on() like this

$("body").on("validate", "#thisForm", function() {

});

Edit to address comments below:

If you cannot delegate the event through parent elements, you must bind the event handler after it is placed into the DOM. Here is an example using jQuery:

$("addmyHTMLhere").html('<form></form>').find('form').validate({put your validate stuff here});

7 Comments

Umm... not much luck with this. Still no validation. BTW. I use: $(document).ready(function() { right at the top of my .js file
Using $(document).ready() will only attach handlers to the existing DOM elements on the initial page load. If you have scripts that dynamically add a form, this form will not have a handler attached. @Raul Juarez gave a good suggestion above. If the .on() does not delegate your event, have a callback function attach the .validate() event handler after the element has been placed on the DOM
Is there anything else I should be doing? I did just what you suggested, but the validation still will not work.
Post your code of when the form is dynamically added, and I can help you attach a handler if you'd like.
The form is a simple one field form. It is added by another function like this success: function(html){self.parent("div").after(html['return']);}, The form is returned as json. The validation is the same as in my question.
|
0

Ran into the same issue, not sure if there is a better way of doing what you want, but this is what I came up with:

$(document.body).on('submit', '#myform', function(e){

    // Set your validation settings and initialize the validate plugin on the form.
    $(this).validate({
        submitHandler: function(form) {
            // do your ajax submit or whatever you want.
        }
    });

    // submit the form pro grammatically.
    $(this).submit();
});

again maybe there is a better way of doing this, but that is what I figured out to work well so far.

Comments

0

I also had this problem when loading the form via AJAX and also wanting to submit the form with AJAX (to stay on current page...). This worked for me:

//Newbie note: ajaxFormCallback is the callback function - which runs once my AJAX loaded form has been added to the page.

var ajaxFormCallback = function(){
    var form = $('#form-id-here');

    form.validate({
        rules: {
            'name': {
                required: true
            },
            'email': {
                required: true,
                email: true
            }
        },
        messages: {
            'name': {
                required: 'Name is required'
            },
            'email': {
                required: 'Email address is required',
                email: 'Invalid email address'
            }
        },
        submitHandler: function(form){
            //submit form via AJAX
            $.ajax({
                type: 'POST',
                url: '/path/to/submit/form/?' + $(form).serialize() + '&ajax=1',
                success: function(data){
                    //replace my form with a response:
                    $(form).parents('.response').replaceWith(data);
                }
            });
        }
    });
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.