ASP.NET MVC 中的选择性客户端验证

发布于 08-19 11:17 字数 109 浏览 7 评论 0原文

如何使用 MVC 2 内置验证系统实现选择性客户端验证

假设我的表单标题中有一个复选框“您有孩子吗?”
,如果选中,则下面的文本框应为必填
(标题为“孩子数量”的文本框)。

How can I implement selective client side validation
using MVC 2 built-in validation system?

Assume I have a checkbox in my form title "Do you have any child?"
and if checked the textbox below it should be required
(textbox titled Number of children).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我不在是我2024-08-26 11:17:36

一些可能会让您思考的选项。在多个发布操作的情况下(例如,单击表单上的取消按钮不应触发验证),我已确保表单仅发布一个操作,而其他任何内容本质上都是样式链接。在这种情况下,验证不会触发。

如果像您的情况一样,您有复杂的验证,我建议创建一个自定义验证器并注册一个客户端适配器,例如,

[RequiredIfHasChildren]

因此您将编写一个自定义验证属性、一个自定义模型验证器和一些 JavaScript 代码来注册一个新客户端侧面验证器。这种方法过去对我有用,但对另一个模型属性的依赖可能有点问题。

希望这有帮助。

A few options that might get you thinking here. In the case of multiple post actions (e.g. clicking cancel button on a form shouldn't fire validation) I have made sure that forms only post one actions and anything else is essentially a styled link. Validation won't fire in this case.

If, as is in your case, you have complex validation I would suggest creating a custom validator and registering a client side adapter e.g.

[RequiredIfHasChildren]

So you'd be writing a custom validation attribute, a custom model validator and some JavaScript code to register a new client side validator. This sort of approach has worked for me in the past but the dependency on another model property can be a bit of a problem.

Hopefully this helps.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文