将 jQuery 验证器规则添加到 ASP 中动态创建的元素
我在 MVC3 项目的页面上有一些动态插入的表单字段。通常我们会在服务器端添加 jQuery 验证,但在这种情况下我们不能(UI 中的多个字段生成一个隐藏字段的值 - 这就是提交的内容。我们无法针对隐藏字段进行验证,因此我们必须为用户可以看到的字段添加仅 UI 验证)
将字段动态添加到页面后,我在容器上运行以下代码:
$container.find(".date").rules("add", {
required: true,
messages: {
required: "The date is required"
}
});
但它不起作用!奇怪的是,禁用上面的代码,创建动态元素,然后在浏览器 JS 控制台中运行代码可以工作,但只显示默认的验证消息。
我不知所措。有什么想法吗?
我正在使用 jQuery Validation 1.9.0 &不引人注目的插件
I've got some dynamically inserted form fields on a page in an MVC3 project. Normally we would add the jQuery validation server-side, but in this case we can't (multiple fields in the UI generate the value for one hidden field - and this is what is submitted. We can't validate against a hidden field, so we must instead add UI-only validation for the fields the user can see)
Once the fields are dynamically added to the page, I run the following code over the container:
$container.find(".date").rules("add", {
required: true,
messages: {
required: "The date is required"
}
});
But it doesn't work! Oddly enough, disabling the above code, creating the dynamic elements, then running the code in the browser JS console works, but only the default validation message shows.
I'm at a loss. Any ideas?
I am using jQuery Validation 1.9.0 & the unobtrusive plugin
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
事实证明,这主要可以在 HTML 中通过向每个表单元素添加一些属性来完成:
name
属性data-val="true"
data -val-required="message"
就像这样:
然后只需通过 JS 重新解析表单即可:
As it turns out, this can be done mostly in HTML by adding a few attributes to each form element:
name
attributedata-val="true"
data-val-required="message"
Like so:
Then the form just needs to be re-parsed via JS:
现在我了解了 Unobtrusive 插件方面的情况(我知道这与 ASP.NET 某种程度上有关),您需要执行以下操作:
添加新元素后,调用
$.validator.unobtrusive .parseElement(newElement)
它将被添加到表单中。正如您的答案所建议的,您需要在新的表单元素中设置 data-val 和 data-val-required 属性。所以你最终会得到这样的结果:
这里显示: http://jsfiddle.net/ryleyb/LNjtd/2/
Now that I understand what's going on with the Unobtrusive plugin side of things (which I understand is related to ASP.NET somehow), here's what you need to do:
After you add your new element, call
$.validator.unobtrusive.parseElement(newElement)
and it will get added to the form. As your answer suggested, you need to set the data-val and data-val-required attributes in the new form element.So you end up with this:
Shown here: http://jsfiddle.net/ryleyb/LNjtd/2/
我认为你有一些更简单的错误 - 就像你的
find('.date')
实际上没有找到任何东西。因为否则的话,你的代码对我来说看起来很合理。这是一个按您预期工作的示例: http://jsfiddle.net/ryleyb/LNjtd/我能够通过以下方式正确验证代码:
I think you had something more simple wrong - like your
find('.date')
wasn't actually finding anything. Because otherwise, your code looks quite reasonable to me. Here is an example of it working as you expected: http://jsfiddle.net/ryleyb/LNjtd/I was able to validate the code correctly with this: