如何在 $.ajax() 中或之前强制进行客户端验证
我有一个表单并启用了不显眼的验证。默认情况下,在提交方法中会触发客户端验证,并且(如果有任何错误)表单如下所示:
验证甚至在任何数据发送到服务器之前就发生。
现在,如果您想使用 $.ajax 方法,此行为将不起作用。客户端验证不起作用。您必须手动检查 javascript 中的所有字段,从而失去了 DataAnnotations 的所有优点。
还有更好的解决办法吗?我可以使用 jquery 的 submit() 但我想它没有像 $.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:
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
哦...
Oh...
在检查表单是否有效之前,您必须强制表单进行验证。像这样的东西:
You must force the form to validate before checking if it is valid. Something like this:
我做了...
如果您有一个带有插件的文本框,可以将这些文本框变成日历控件,这似乎也是一个很好的解决方案。我这样说的唯一原因是因为我将 Zebra Datepicker 与 MVC 表单一起使用,如果焦点位于日历日期选择器上,它将提交无效表单。使用下面的代码可以阻止这种情况。
I did...
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.
我遇到了与 Yablargo 相同的问题,它说 valid 不是一个函数,所以我想出了这个:
对于提交按钮的 onclick 处理程序,我输入:
onclick="return $(this)。最接近('形式')。checkValidity();”
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();"