Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use the Data Validation Attributes in C# in a non-ASP.net context?

I'd like to use the data validation attributes in a library assembly, so that any consumer of the data can validate it without using a ModelBinder (in a console application, for instance). How can I do it?

like image 789
Chris McCall Avatar asked Sep 23 '10 21:09

Chris McCall


People also ask

What are validation attributes?

Validation attributes let you specify the error message to be displayed for invalid input. For example: C# Copy. [StringLength(8, ErrorMessage = "Name length can't be more than 8.")]

How do you use data annotations?

Data annotations (available as part of the System. ComponentModel. DataAnnotations namespace) are attributes that can be applied to classes or class members to specify the relationship between classes, describe how the data is to be displayed in the UI, and specify validation rules.


1 Answers

Actually this is pretty cool. I used it in a WFP validation implementation recently. Most people end up writing lots of code using reflection to iterate the attributes, but there's a built in function for this.

var vc = new ValidationContext(myObject, null, null); return Validator.TryValidateObject(myObject, vc, null, true); 

You can also validate attributes on a single named property. You can also optionally pass in a list in order to access the error messages :

var results = new List<ValidationResult>(); var vc = new ValidationContext(myObject, null, null) { MemberName = "UserName"}; var isValid = Validator.TryValidateProperty(value, vc, results);  // get all the errors var errors = Array.ConvertAll(results.ToArray(), o => o.ErrorMessage); 
like image 188
TheCodeKing Avatar answered Oct 11 '22 08:10

TheCodeKing