1

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

Community
  • 1
  • 1
Colin
  • 22,328
  • 17
  • 103
  • 197

1 Answers1

2

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'
}
politus
  • 5,996
  • 1
  • 33
  • 42