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

4

12

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.

Smashandgrab answered 24/5, 2011 at 16:37 Comment(0)
S
12

Oh...

if (form.valid()) // do submit
Smashandgrab answered 24/5, 2011 at 17:10 Comment(4)
For some reason, I get .valid() is not a function even though my client side validation is working normally :( aghhhSilurid
@Silurid I also use this technique xhalent.wordpress.com/2011/01/24/…Smashandgrab
Ended up figuring out the issue, it was due to 2 different jquery being loaded inadvertentlySilurid
oh yeah... I've been through thatSmashandgrab
C
2

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

var form = $( "#myform" );
form.validate();
if (form.valid()) {
    // ...
}
Catechist answered 26/11, 2013 at 12:52 Comment(0)
P
2

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.

Peduncle answered 9/5, 2016 at 14:42 Comment(1)
I had a completely different problem but your e.preventDefault(); pointed me in the right direction... along with $('#form').on('submit', function (e) { code });.Anagnos
A
0

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();"

Animal answered 7/9, 2012 at 16:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.