How to force form client-side validation in or bef

2019-01-26 06:33发布

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.

4条回答
你好瞎i
2楼-- · 2019-01-26 06:42

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楼-- · 2019-01-26 06:50

Oh...

if (form.valid()) // do submit
查看更多
干净又极端
4楼-- · 2019-01-26 06:50

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

查看更多
爷、活的狠高调
5楼-- · 2019-01-26 06:51

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.

查看更多
登录 后发表回答