iLemming
iLemming

Reputation: 36254

How to force form client-side validation in or before $.ajax()

I have a form and unobtrusive validations are enabled. By default in submit method client side validation gets triggered and (if you have any errors) the form looks like this:

enter image description here

The validation happens even before any data gets sent to the server.

Now this behavior doesn't work if you want to use $.ajax method. Client side validation doesn't work. You have to manually check all the fields in your javascript, losing all the beauty of DataAnnotations.

Is there any better solution? I could've use jquery's submit() but I guess it doesn't have callback like $.ajax.

Upvotes: 12

Views: 16127

Answers (4)

Mike Upjohn
Mike Upjohn

Reputation: 1297

I did...

$("#form-submit-button").click(function (e) {
    e.preventDefault(); // Stops the form automatically submitting
    if ($("#my-form").valid()) {
        $("#my-form").submit();
    }
});

This also seems to be a good solution if you have say textboxes with a plugin to make those textboxes into a calendar control. Only reason I say this is because I used Zebra Datepicker with an MVC form and it would submit an invalid form if focus was on the calendar date picker. Using the below code stops this.

Upvotes: 2

Daniele Armanasco
Daniele Armanasco

Reputation: 7451

You must force the form to validate before checking if it is valid. Something like this:

var form = $( "#myform" );
form.validate();
if (form.valid()) {
    // ...
}

Upvotes: 2

vbullinger
vbullinger

Reputation: 4266

I was having the same issue Yablargo was having in that it was saying that valid is not a function, so I came up with this:

For the onclick handler of the submit button, I put this:

onclick="return $(this).closest('form').checkValidity();"

Upvotes: 0

iLemming
iLemming

Reputation: 36254

Oh...

if (form.valid()) // do submit

Upvotes: 12

Related Questions