オブジェクトの一部のプロパティが検証属性を持つクラスであるなど、DataAnnotation属性をオブジェクトグラフに散布しています。次のシナリオでDataAnnotations:オブジェクトグラフ全体を再帰的に検証する
:
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; }
}
私はPostalCode
ためEmployee
のAddress
値のないを検証しようとした場合は、その後、私は好き(と期待)例外を、私は何を得ないだろう。ここで私はそれをやっている方法は次のとおりです。
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));
すべてのプロパティを再帰的にを検証していることを確認することを、他のどのようなオプション私がValidator
を持っていますか?
事前に感謝します。
+1良いソリューション – Jehof
いいですが、コレクションはどうですか?この 'public IList
Addresses'のようなプロパティを検証することは素晴らしいことです。とにかく、解決のおかげで。 – altsoこの属性は評価されていません。 –