Validation using Attributes in C#
Orsan Awawdi
Software Engineer | Extensive experience in automation using Python and Jenkins
Validating data entered by user can be done via multiple methods. Attributes is one powerful yet simple way to validate input, when working with C#
This code sample describes a user defined Customer and Address classes. As can be seen, some of the properties are annotated with special attributes. These attributes are part of System.ComponentModel.DataAnnotations. Attributes can be placed by the name of the attribute enclosed in square brackets ([]) above the declaration of the entity to which it applies. Here is an example of Attributes used inside Customer and Address classes.
Upon instantiation of the entity (here done by me, but can be as an input from user), data will be validated against the rules specified in the Attributes.
All I need to do now, is to fire TryValidateObject method, which takes the newly constructed object (Customer) as an argument, together with Validation Context and a List of Validation result variables. In case user enters, say, First Name as empty, validation will fail and a relevant error message will be shown. Powerful yet simple.