Pages

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**** ).

How to use Attribute

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.

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.