Introduction
In this tutorial, we learn how to use the Data Annotation validators to perform validation in a .NET application. The greatest advantage of using the Data Annotation validators is that they enable us to perform validation simply by adding one or more attributes like the Required or String Length attribute - on the class property.
The System.ComponentModel.DataAnnotations namespace provides attribute classes that are used to define metadata for Dynamic Data controls. With the help of Data annotation, we can centralize the data definition and do not repeat the same rules in multiple places.
The data annotation attributes fall into three categories:
- Validation attributes,
- Display attributes,
- Data modeling attributes.
How to Perform Validation on custom Model or custom Class
The Data Validation is the heart of any application.
The steps to create a Validation Frame are as follows.
Step 1: Data Anotation is in the namespace System.ComponentModel.DataAnnotations, so this must be added as a reference to your application.
Step 2: Create an Interface, all model class on which we want to perform Validation, all the classes inherit from this interface.
public interface IEntity
{
}
public class DataClass : IEntity
{
....
....
....
}
Step 3: Create a class called "EntityValidationResult" which has methods "HasError'" and one parameterized constructor.
Serializable]
public class EntityValidationResult
{
public IList<ValidationResult> ValidationErrors { get; private set; }
public bool HasError
{
get { return ValidationErrors.Count > 0; }
}
public EntityValidationResult(IList<ValidationResult> violations = null)
{
ValidationErrors = violations ?? new List<ValidationResult>();
}
}
Step 4: Create a validation mechanism:
public class DataAnnotation
{
public static EntityValidationResult ValidateEntity<T>(T entity) where T : IEntity
{
return new EntityValidator<T>().Validate(entity);
}
}
public class EntityValidator<T> where T : IEntity
{
public EntityValidationResult Validate(T entity)
{
var validationResults = new List<ValidationResult>();
var vc = new ValidationContext(entity, null, null);
var isValid = Validator.TryValidateObject(entity, vc, validationResults, true);
return new EntityValidationResult(validationResults);
}
}
Step 5: Create a model as per your requirements:
In this current example I have created a DataClass and it has various properties such as Name, Address, email Address and Age. And include a validation attribute on top of the property.
public class DataClass : IEntity
{
[Required(AllowEmptyStrings = false, ErrorMessage = "Name is Required Field.")]
public string Name { get; set; }
[StringLength(20, MinimumLength = 4, ErrorMessage = "Address Length Between 4 to 20 character")]
public string AddressLine1 { get; set; }
[RegularExpression(@"^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$", ErrorMessage = "Email Address is not Valid.")]
public string EmailAddress { get; set; }
[Range(1, 90)]
public int Age { get; set; }
}
Data Annotation supports some builtin validation attributes which are listed below:
http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.aspx
Example:
In the following example I have assigned some data to the class property and validated that:
DataClass myDataClass = new DataClass();
myDataClass.AddressLine1 = "Jignesh Trivedi Test for C - Sharp Corner";
myDataClass.EmailAddress = "jig";
var validationResult = DataAnnotation.ValidateEntity<DataClass>(myDataClass);
if (validationResult.HasError)
{
Console.WriteLine("Validation Error : ");
foreach (var error in validationResult.ValidationErrors)
{
Console.WriteLine(error.ErrorMessage);
}
}
Console.Read();
Output of the above example:
Conclusion
With the help of Data Annotation, it is very easy to create a validating model and we can write a centralized mechanism for validation; this will help to reduce code size as well as code re-usability. In other frameworks like ASP.NET MVC or WCF RIA Services we can also implement such validators.