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

谁都会走 提交于 2019-11-28 03:03:06

问题


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:

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.


回答1:


Oh...

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



回答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()) {
    // ...
}



回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/6113788/how-to-force-form-client-side-validation-in-or-before-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!