Validation in Any Type of Application Using DataAnnotation

DataAnotation NameSpace

System.ComponentModel

The DataAnnotation namespace provides attribute classes decorating a class property that is useful for validating the class object. Besides the attribute classes it also provides a set of classes that is helpful for validating class (for example Validator, ValidationContext and VlidationResult, in other words all classes that start with Validat****).

The following image shows all the classes provided by DataAnnotation.



The image shows all classes not related to validation.

Find more about each class on MSDN.

How to use Attribute

Before starting, read the following article about creating a custom attribute:

Now to use an Attribute in your entity you need to decorate your property of entity with the attribute as in the following:

  1.    public class BankAccount  
  2.    {  
  3.   
  4.        public enum AccountType  
  5.        {  
  6.            Saving,  
  7.            Current  
  8.        }  
  9.   
  10.        [Required(ErrorMessage="First Name Required")]  
  11.        [MaxLength(15,ErrorMessage="First Name should not more than 1`5 character")]  
  12.        [MinLength(3,ErrorMessage="First Name should be more than 3 character")]  
  13.        public string AccountHolderFirstName { getset; }  
  14.   
  15.        [Required(ErrorMessage="Last Name Required")]  
  16.        [MaxLength(15,ErrorMessage="Last Name should not more than 1`5 character")]  
  17.        [MinLength(3,ErrorMessage="Last Name should be more than 3 character")]  
  18.        public string AccountHolderLastName { getset; }  
  19.   
  20.        [Required]  
  21. [RegularExpression("^[0-9]+$", ErrorMessage = "Only Number allowed in AccountNumber")]  
  22.        public string AccountNumber { getset; }  
  23.   
  24.        public AccountType AcType { getset; }  
  25.   
  26.        [AccountBalaceCheckAttribute]  
  27.        public double AccountBalance { getset; }  
  28.    }   

As in the preceding code, the BankAccount entity property is decorated with the Attribute and also provided with the proper error message.

In code, the AccountBalance property is decorated with the Entity Specific custom validation attribute. To read more please refer to the custom attribute link listed above.

How to validate

To validate an entity, DataAnnotation provides a class called Validator that allows validation of an entity as listed in the following code.

  1. public class GenericValidator   
  2. {  
  3.     public static bool TryValidate(object obj, out ICollection<ValidationResult> results)  
  4.     {  
  5.         var context = new ValidationContext(obj, serviceProvider: null, items: null);  
  6.         results = new List<ValidationResult>();  
  7.         return Validator.TryValidateObject(  
  8.             obj, context, results,  
  9.             validateAllProperties: true  
  10.         );  
  11.     }  
  12. }  

The preceding code shows the code for the GenericValidator class that is a class to validate any entity. The class is used to avoid writing code again and again when doing validation.

The preceding code uses the Validator class with a TryValidateObject method that takes the ValidationContext class object as input.

The following code shows how to use the GenericValidator class for validating the entity.

  1. static void Main(string[] args)  
  2. {  
  3.     var bankAccount = new BankAccount();  
  4.     ICollection<ValidationResult> lstvalidationResult;  
  5.   
  6.     bool valid = GenericValidator.TryValidate(bankAccount, out lstvalidationResult);  
  7.     if (!valid)  
  8.     {  
  9.         foreach (ValidationResult res in lstvalidationResult)  
  10.         {  
  11.             Console.WriteLine(res.MemberNames +":"+ res.ErrorMessage);  
  12.         }  
  13.           
  14.     }  
  15.     Console.ReadLine();  
  16. }  

Output



Conclusion

The ValidationAttribute is one way to do validation (Aspect Oriented Programming) using attributes. And the validation attribute provided in the DataAnnotation namespace can be used in any application to do the validation of an entity.


Similar Articles