Search code examples
jqueryjquery-validateunobtrusive-validationjquery-forms-plugin

How to load a form using ajax, validate it then submit it using ajax?


I am opening a jQuery dialog containing a form that is loaded by an ajax call triggered when the dialog is opened. When the user clicks OK I want to validate the form before submitting it using ajax. Here is the callback assigned to the OK button:

var dialogOK = function () {
    var $form = $(this).find("form:first");
    if ($form.find("input:first").length > 0) {
        $form.removeData("validator").removeData("unobtrusiveValidation");
        $.validator.unobtrusive.parse($form);
        $form.validate({
            submitHandler: function (form) {
                alert("This alert doesn't appear");
            },
            invalidHandler: function (event, validator) {
                alert("Neither does this one");
            }
        });
        if ($form.valid) {
            alert("form.valid says it's valid when it's not");
            //$form.submit(); //when this is called the client-side 
                             //validation works and the form is not submitted
            //but when I call ajaxSubmit (forms jQuery plugin)
            //the form is submitted
            $form.ajaxSubmit({
                success: function () {
                    alert("And I still need to work out how to check whether 
                        server-side validation passed before I close the dialog");
                }
            });
        }

    }
    else {
        $(this).dialog("close");
    }
};

I have based the code on this question but I can't work out how to get the client-side validation to fire when doing an ajax submit.

I am using jquery-1.9.1, jquery.unobtrusive-ajax, jquery.validate and jquery.form


Solution

  • you need to check the value of the plugin method valid so you need this

    if ($form.valid()) 
    {
      // do stuff
    }
    

    not this

    if ($form.valid) 
    {
      // always true, as presence of the plugin method is 'truthy'
    }