的DataAnnotations:递归验证整个对象图 [英] DataAnnotations: Recursively validating an entire object graph
问题描述
我撒了DataAnnotation属性,其中对象的某些属性,它本身具有验证属性类等对象图。
I have an object graph sprinkled with DataAnnotation attributes, where some properties of objects are classes which themselves have validation attributes, and so on.
在以下情形:
public class Employee
{
[Required]
public string Name { get; set; }
[Required]
public Address Address { get; set; }
}
public class Address
{
[Required]
public string Line1 { get; set; }
public string Line2 { get; set; }
[Required]
public string Town { get; set; }
[Required]
public string PostalCode { get; set; }
}
如果我试图验证一个员工
的地址
与没有价值邮政code
,那么我想(和期望)一个例外,但我得到没有。下面是我怎么做的:
If I try to validate an Employee
's Address
with no value for PostalCode
, then I would like (and expect) an exception, but I get none. Here's how I'm doing it:
var employee = new Employee
{
Name = "Neil Barnwell",
Address = new Address
{
Line1 = "My Road",
Town = "My Town",
PostalCode = "" // <- INVALID!
}
};
Validator.ValidateObject(employee, new ValidationContext(employee, null, null));
做什么其他的选择,我有验证
,以确保所有的属性被验证的递归的?
What other options do I have with Validator
that would ensure all properties are validated recursively?
在预先感谢。
推荐答案
我的回答得到了太长时间放在这里,所以我把它变成一个博客帖子:)
My answer got too long to put here, so I turned it into a blog post :)
<一个href="http://www.technofattie.com/2011/10/05/recursive-validation-using-dataannotations.html">Recursive验证使用的DataAnnotations
该解决方案为您提供了一种方法使用您现在正在使用相同的基本方法来实现递归的验证。
The solution gives you a way to achieve recursive validation using the same basic method you are using now.
这篇关于的DataAnnotations:递归验证整个对象图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!