Link: http://www.feeldesignstudio.com/2013/08/data-annotations-manual
DataAnnotations are very useful in ASP. net mvc, but in other cases, such as console programs, how can we use it and directly code it, a super simple class:
C #
publicclassCustomer{ [Required] publicstringName{get;set;} [Required] publicstringPhone{get;set;} [Required] publicstringEmail{get;set;}}
The following is the verification code:
C #
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); }}
To implement IValidatableObject, you can also:
C #
publicclassCustomer:IValidatableObject { [Required] publicstringName{get;set;} [Required] publicstringPhone{get;set;} [Required] publicstringEmail{get;set;} publicIEnumerable<ValidationResult>Validate(ValidationContext validationContext) { ... } }