使用不显眼的验证适用于单个元素,但不适用于整个表单
使用 Asp.Net MVC3 进行不显眼的验证。我有一个带有几个输入字段的表单。其中一个字段非常简单:
<input id="Name" class="valid" type="text" value="" name="Name" data-val-required="Enter your name." data-val-length-min="5" data-val-length-max="50" data-val-length="Enter a valid name." data-val="true">
然后我有一些 js 来验证表单并仅在客户端验证通过时才提交它,如下所示:
var $form = $('#contact_form');
var formAction = $form.attr('action');
var serialized = $form.serialize();
if ($form.validate().valid()) {...
现在最后一行总是返回 true (是的,我启用了不显眼的功能)。但是,如果我将最后一行更改为:
if ($form.validate().element('#Name')) { ...
它效果很好并返回 false。我有很多字段,不想遍历每个字段,并且很困惑为什么在验证整个表单时它说 true 但验证每个单独元素正确返回 false 。
我尝试过的事情: - 通过 unobtrusive 的 $.validator.parse(... 重新解析表单,但无济于事。它不是动态表单,在页面加载时呈现。
注意:我还检查了 jquery (v1.6.2) jquery.validate.min .js (v1.8.1) 和 jquery.validate.unobtrusive.min.js 已加载到浏览器中。
Using Asp.Net MVC3 with unobtrusive validation. I have a form that has a few input fields. One of the fields is pretty simple:
<input id="Name" class="valid" type="text" value="" name="Name" data-val-required="Enter your name." data-val-length-min="5" data-val-length-max="50" data-val-length="Enter a valid name." data-val="true">
I then have some js that validates the form and submits it only if client-side validation passes as in:
var $form = $('#contact_form');
var formAction = $form.attr('action');
var serialized = $form.serialize();
if ($form.validate().valid()) {...
Now the last line always returns true (yes I have unobtrusive enabled). However if I change the last line to:
if ($form.validate().element('#Name')) { ...
It works great and returns false. I have many fields and don't want to iterate over each one and am confused as to why when validating the whole form it says true but validating each individual element returns false correctly.
Things I tried:
- reparsing the the form via unobtrusive's $.validator.parse(... to no avail. It's not a dynamic form and gets rendered when the page loads.
Note: I also checked that jquery (v1.6.2) jquery.validate.min.js (v1.8.1) and jquery.validate.unobtrusive.min.js are loaded in the browser.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不必调用
.validate()
而是直接调用.valid()
:You don't have to call
.validate()
but directly.valid()
: