如何对模型对象执行复杂的验证?

发布于 2025-01-04 04:00:42 字数 632 浏览 3 评论 0原文

我的项目位于 ASP.NET MVC 3 中。在我的域中,我有一个由实体框架定义的模型对象。为了验证属性,我只需扩展生成的 EF 对象并添加一个包含所有验证属性的元数据类。

[MetadataType(typeof(ContactInformationMetaData))]
public partial class ContactInformation
{

}

public class ContactInformationMetaData
{
    [Required]
    public string FirstName { get; set; }

    [Required]
    public string LastName { get; set; }

    public string Phone { get; set; }

    [EmailValidator]
    public string Email { get; set; }
}

这在大多数情况下都很有效,但现在我有一个更复杂的场景。我不希望“电话”和“电子邮件”属性是必需的,但我希望其中之一是必需的。换句话说,我想要求设置电子邮件或电话或两者都设置,但不能都不设置。

我将如何执行这样的复杂验证?如果我创建一个自定义验证属性,我应该把它放在哪里以及它如何工作?

My project is in ASP.NET MVC 3. In my domain I have a model object defined by Entity Framework. In order to validate properties I simply extend the generated EF object and add a metadata class which contains all my validation attributes.

[MetadataType(typeof(ContactInformationMetaData))]
public partial class ContactInformation
{

}

public class ContactInformationMetaData
{
    [Required]
    public string FirstName { get; set; }

    [Required]
    public string LastName { get; set; }

    public string Phone { get; set; }

    [EmailValidator]
    public string Email { get; set; }
}

This works great most of the time but now I have a more complex scenario. I don't want the Phone and Email properties to be required but I want ONE of them to be required. In other words, I want to require that either email or phone or both be set, but not none.

How would I perform complex validation like this? If I create a custom validation attribute where would I put it and how would that work?

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

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

发布评论

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

评论(2

舟遥客 2025-01-11 04:00:42

这是另一个完全类似的问题(甚至电话和电子邮件示例也是相同的):
模型验证/ASP.NET MVC 3 - 条件必需属性

Here is another question exactly like that (even the Phone and Email example is the same):
Model Validation / ASP.NET MVC 3 - Conditional Required Attribute

动次打次papapa 2025-01-11 04:00:42

查看 FluentValidation:

http://fluentvalidation.codeplex.com/wikipage?title=mvc

您可以轻松创建这种类型的自定义验证,总的来说,这是一个非常酷的验证框架

Check out FluentValidation:

http://fluentvalidation.codeplex.com/wikipage?title=mvc

you can easily create this type of custom validation, it's a pretty cool validation framework in general

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