If you work in MVC you will observe that all the model validation is attribute-based. In the past few days I have been working on a website architecture developed in ASP.NET 4.0 where I implemented attribute-based validation of a Data Model. To make the article simple I will explain it here using a console application with simple code. Let's start with a data model class:
- public class Model
- {
- public string JobName { get; set; }
- public string DeptName { get; set; }
- public string EmpName { get; set; }
- }
Here the requirement is that the Job Name Is mandatory and Dept Name is mandatory and its maximum length cannot be greater than 3 . A very obvious way to do it is to check all the conditions using IF-ELSE but It will increase the line of codes one needs to put IF – ELSE everywhere in the model class. To simplify it let's make two custom attributes that will validate the data model.
- [AttributeUsage(AttributeTargets.Field|AttributeTargets.Property)]
- public class Requierd:Attribute
- {
- public string ErrorMessage { get; set; }
- public Requierd(string errorMessage)
- {
- this.ErrorMessage = errorMessage;
- }
- }
- [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
- public class MaxLength : Attribute
- {
- public string ErrorMessage { get; set; }
- public int Length { get; set; }
- public MaxLength(string errorMessage,int MaximumLength)
- {
- this.ErrorMessage = errorMessage;
- this.Length = MaximumLength;
- }
- }
Now we need one more class that will read the property value, validate it and show the Error message through Reflection.
- public class EntityBase
- {
- public List<string> BrokenRules = null;
- public EntityBase()
- {
- BrokenRules = new List<string>();
- }
- public bool Validate()
- {
- bool IsValid = true;
- PropertyInfo[] PropInfo = this.GetType().GetProperties();
- foreach (PropertyInfo info in PropInfo)
- {
- object data = info.GetValue(this, null);
-
- foreach (object RequiredAttribute in info.GetCustomAttributes(typeof(Requierd), true))
- {
- if (data == null)
- {
- IsValid = false;
- BrokenRules.Add((RequiredAttribute as Requierd).ErrorMessage);
- }
- }
- foreach (object MaxLengthAttribute in info.GetCustomAttributes(typeof(MaxLength), true))
- {
- if (data != null)
- {
- if (data.ToString().Length > (MaxLengthAttribute as MaxLength).Length)
- {
- IsValid = false;
- BrokenRules.Add((MaxLengthAttribute as MaxLength).ErrorMessage.ToString());
-
- }
- }
- }
- }
- return IsValid;
- }
- }
Until now our Validation Attribute is ready, The Entity Base class is ready to validate . Let's return to the model class where we will implement it.
- public class Model : EntityBase
- {
- [Requierd("Job Name Is Requierd")]
- public string JobName { get; set; }
- [Requierd("DeptName Is Requierd")]
- [MaxLength("DeptName should not be greater than 3",3)]
- public string DeptName { get; set; }
- public string EmpName { get; set; }
- }
Time to initialize the model class from the Main class and call the validation function.
- static void Main(string[] args)
- {
- Model obj = new Model();
- obj.JobName = "Coder";
- obj.DeptName = "Computer Science";
- if (!obj.Validate())
- {
- foreach (string message in obj.BrokenRules)
- {
- Console.WriteLine(message);
- }
- }
- Console.Read();
- }
In the Model class we have put the required attribute on JobName and DeptName and MaxLength attribute with max Length of 3 on Dept name, the Required attribute will successfully pass through but the Max Length Validation will fail because the length of Computer Science is more than 3.