如何对模型对象执行复杂的验证?
我的项目位于 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是另一个完全类似的问题(甚至电话和电子邮件示例也是相同的):
模型验证/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
查看 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