Pranay Rana: Validation in any type Application using DataAnnotation

Saturday, March 7, 2015

Validation in any type Application using DataAnnotation

DataAnotation NameSpace

System.ComponentModel. DataAnnotation namespace that provides set of attributes classes used for decorating class property with it, which is useful for validating class object. Besides attribute classes it also provide set of class which is helpful for validating class (Ex. Validator, ValidationContext, VlidationResult i.e. all classes with start with Validat**** ).

Below image show the all classes provided by DataAnnotation



Image shows the all classes not related to validation.

Find more about each class on MSDN : https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations%28v=vs.95%29.aspx

How to use Attribute

Before start look this for creating custom attribute : Custom Validation Attribute Specific to Entity

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

    public class BankAccount
    {

        public enum AccountType
        {
            Saving,
            Current
        }

        [Required(ErrorMessage="First Name Required")]
        [MaxLength(15,ErrorMessage="First Name should not more than 1`5 character")]
        [MinLength(3,ErrorMessage="First Name should be more than 3 character")]
        public string AccountHolderFirstName { get; set; }

        [Required(ErrorMessage="Last Name Required")]
        [MaxLength(15,ErrorMessage="Last Name should not more than 1`5 character")]
        [MinLength(3,ErrorMessage="Last Name should be more than 3 character")]
        public string AccountHolderLastName { get; set; }

        [Required]
        [RegularExpression("^[0-9]+$", ErrorMessage = "Only Number allowed in AccountNumber")]
        public string AccountNumber { get; set; }

        public AccountType AcType { get; set; }

        [AccountBalaceCheckAttribute]
        public double AccountBalance { get; set; }
    } 

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

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

How to validate

To validate entity DataAnnotation provides class called Validator, which allow to validate entity as listed in below code.

public class GenericValidator 
    {
        public static bool TryValidate(object obj, out ICollection results)
        {
            var context = new ValidationContext(obj, serviceProvider: null, items: null);
            results = new List();
            return Validator.TryValidateObject(
                obj, context, results,
                validateAllProperties: true
            );
        }
    }

Above code shows code for GenericValidator class , which is class to validate any entity. Class used to avoid writing code again and again when doing validation.

Above code class make use of Validator class with it TryValidateObject method which takes ValidationContext class object as input.

Below code shows how to use GenericValidator class for validating entity.

static void Main(string[] args)
        {
            var bankAccount = new BankAccount();
            ICollection lstvalidationResult;

            bool valid = GenericValidator.TryValidate(bankAccount, out lstvalidationResult);
            if (!valid)
            {
                foreach (ValidationResult res in lstvalidationResult)
                {
                    Console.WriteLine(res.MemberNames +":"+ res.ErrorMessage);
                }
                
            }
            Console.ReadLine();
        }

Output 

Conclusion

ValidationAttribute is doing one way to achieve Validation (Aspect Oriented Programming) with the help of attribute. And validation attribute provided in DataAnnotation namespace can be used in any time of application to do validation of entity.

No comments:

Post a Comment