用于视图模型的 Asp.NET MVC 自定义验证器?

发布于 2024-08-03 18:31:35 字数 850 浏览 7 评论 0原文

我使用自定义视图模型类作为 DTO 对象来保存要在视图页面上显示的数据。我已通过 DataAnnotations 库应用验证来对这些类的属性执行服务器端验证。这是一个简单的示例:

[DisplayName("Customer Account Id")]
[Required(ErrorMessage = "* Account Number is required")]
[StringLength(16, ErrorMessage = "* Account Number must be 16 characters in length", MinimumLength = 16)]
public string CustomerAccountId { get; set; }

如果有人提交搜索,并且该字段未通过或通过的长度不是 16,则验证失败,并且通过 ValidationMessage HtmlHelper 在页面上显示一条错误消息:

<%= Html.ValidationMessage("CustomerAccountId")%>       

现在我需要添加按帐户 ID 名字/姓氏组合进行搜索的功能。我的问题是:

如何应用条件验证?如果我提交带有名字/姓氏的搜索,我不希望验证失败,因为帐号也没有通过。我找到了链接,其中显示了如何实现自定义验证器,但这似乎适用于 1 个属性。如何传递整个对象模型,并将适当的验证错误消息传回要在页面上显示的适当字段?这可能吗?

I am using custom view model classes as DTO objects to hold data for display on my View pages. I have applied validation via the DataAnnotations library to perform server side validation on the properties of these classes. Here is a simple example:

[DisplayName("Customer Account Id")]
[Required(ErrorMessage = "* Account Number is required")]
[StringLength(16, ErrorMessage = "* Account Number must be 16 characters in length", MinimumLength = 16)]
public string CustomerAccountId { get; set; }

If someone submits a search and this field does not come through or comes through at a length that is not 16, validation fails, and an error message is displayed on the page via the ValidationMessage HtmlHelper:

<%= Html.ValidationMessage("CustomerAccountId")%>       

Now I need to add the ability to search by account id OR a combination of First/Last name. My question is this:

How do I apply conditional validation? If I submit a search with First/Last name, I don't want validation to fail because an account number was not passed through as well. I found this link, which shows how to implement a custom validator, but it seems like this applies to 1 property. How do I pass an entire object model through, and pass back the appropriate validation error messages to the appropriate fields to be displayed on the page? Is this possible?

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

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

发布评论

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

评论(1

机场等船 2024-08-10 18:31:35

您可以实现 IDataErrorInfo。 (文章标题中类名拼写错误,但代码是正确的。)

You can implement IDataErrorInfo. (The class name is misspelled in the article title, but the code is right.)

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