使用Data Annotations进行手动验证
原文链接:http://www.feeldesignstudio.com/2013/08/data-annotations-manual
DataAnnotations在ASP.NET MVC中非常好用,但是其他时候,比如控制台程序,我们怎么来使用它呢,直接上代码,一个超简单的类:
publicclassCustomer { [Required] publicstringName{get;set;} [Required] publicstringPhone{get;set;} [Required] publicstringEmail{get;set;} }
下面是验证的代码:
var cust=newCustomer(); var context=newValidationContext(cust,serviceProvider:null,items:null); var results=newList<ValidationResult>(); var isValid=Validator.TryValidateObject(cust,context,results); if(!isValid) { foreach(var validationResult inresults) { Console.WriteLine(validationResult.ErrorMessage); } }
实现IValidatableObject,也可以:
publicclassCustomer:IValidatableObject { [Required] publicstringName{get;set;} [Required] publicstringPhone{get;set;} [Required] publicstringEmail{get;set;} publicIEnumerable<ValidationResult>Validate(ValidationContext validationContext) { ... } }