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

◇◆丶佛笑我妖孽 提交于 2019-11-29 09:29:46

Oh...

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

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

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

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.

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

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