Using Data Annotations To Perform Validations

Validations are very important to limit user input. So, we need to validate our form client side and server side as well. Developers write the validations through if/else statements again and again to check the data and then they go through the exceptions, this is the way developers normally apply the validations on the forms.

But Data Annotation attributes are a C# built-in feature. Data Annotation Attributes is not a web concept, but we can also use them in our desktop and mobile applications as well. But today, web development is a huge trend so students or beginners should know about it. Don’t limit your mind to use Data Annotations for the web only.

You just need to include the reference to System.ComponentModel.DataAnnotations into your project and you can use Data Annotation Attribute in your business (model) classes. Let’s discuss the classical validation and how the developers were applying the validations before this feature.

  1. public class Student {  
  2.     private string _StudentName;  
  3.     public string StudentName {  
  4.         get {  
  5.             return _StudentName;  
  6.         }  
  7.         set {  
  8.             if (value == null) {  
  9.                 throw new  
  10.                 NullReferenceException("The value should not Null");  
  11.             }  
  12.             _StudentName = value;  
  13.         }  
  14.     }  
  15. }  

Yes, this was the way, whenever they needed to apply the validations on the form they would come into the set block and apply if else statements here.

But with the help of Data Annotations, the code has become so much cleaner and easy to use.

Remember when have the libraries into the framework or outside of the framework available, then use those framework features or libraries because they are tested and they have no bugs but your written code can be broken. So, let’s learn how to use the Data Annotations into our business model class.

Implementation of Data Annotations

Let’s add some different kinds of fields in our class to apply a different kind of validation attribute on it and to learn the most about Data Annotations.

  1. namespace ValidationDemo.Models {  
  2.     public class Student {  
  3.         public string Name {  
  4.             get;  
  5.             set;  
  6.         }  
  7.         public string Email {  
  8.             get;  
  9.             set;  
  10.         }  
  11.         public string RetypeEmail {  
  12.             get;  
  13.             set;  
  14.         }  
  15.         public string Cnic {  
  16.             get;  
  17.             set;  
  18.         }  
  19.         public int Age {  
  20.             get;  
  21.             set;  
  22.         }  
  23.         public string City {  
  24.             get;  
  25.             set;  
  26.         }  
  27.         public DateTime ? DateOfBirth {  
  28.             get;  
  29.             set;  
  30.         }  
  31.     }  
  32. }  

I’ve decorated the model class with these fields.


Required attribute is used to make the fields required.

  1. [Required]   
  2. public string Name {  
  3.     get;  
  4.     set;  
  5. }  

As you can see in the Visual Studio,  [Required] and our Customer class names have the same color, this means that ‘Required’ is also a class. You can see the under-the-hood coding by right-clicking on the ‘Required’ attribute and going to Definition. If you’ve installed Resharper, then you can easily see the coding behind it.

Visual Studio

The code looks like that. We’re using [Required] and here the class name is RequiredAttribute. Don’t get confused among these things, actually, Microsoft makes the word Attribute optional here. Now you just write it as [Required].

Now if we want to define our custom error message and if any user validates the Name field, then we can initialize the ‘ErrorMessage’ Property of any validation attribute class.

  1. [Required] public string Name {  
  2.     get;  
  3.     set;  
  4. }[Required(ErrorMessage = "Please Enter Valid Email Address")]   
  5. public string Email   
  6. {  
  7.     get;  
  8.     set;  
  9. }  


As we already know, email address has its own way, it is necessary that email address should have a domain name with @ sign. So, instead of writing the code for email address field validation, we decorate our email field as:

  1. [EmailAddress]  
  2. public string Email { get; set; }  
Might be you’ve even seen it this way:
  1. [DataType(DataType.EmailAddress)]  
  2. public string Email { get; set; }  
This is actually the old way, now you can write it directly as I did in the first technique.
You might see the form which has another field of Confirm Password. It matches the data from the first field and accepts if both the fields have the same value. In that kind of scenario we can use the Compare attribute.
  1. [Required(ErrorMessage = "Please Enter Valid Email Address")]  
  2. public string Email { get; set; }  
  4. [Compare("Email")]  
  5. public string RetypeEmail { get; set; }  
Don’t be confused about how I’m writing the values for the properties in Compare Attribute. Actually when you make the brackets for attributes above your class properties and write the attribute ‘Compare’ then you’ll see intellisense. Read it carefully, if you want to be a good programmer, then you should know what the system is demanding from you and how it will work; intellisense tells you the whole story. Another thing, now our RetypeEmail property is not required. So you need to mention [Required] attribute as well to make them required. Some developers like this way to mention another attribute.
  1. [Required]  
  2. [Compare("Email")]  
  3. public string RetypeEmail { get; set; }  
But some developers don’t like this way and they prefer this:
  1. [Compare("Email"), Required]  
  2. public string RetypeEmail { get; set; }  
Regular Expressions are used to follow the particular pattern for our properties value. Like in Pakistan, CNIC has the first dash after 5 digits and then the second dash after 7 digits. So this string value has a specific pattern. Now Search on Google and find out Pakistani CNIC Regular Expression. You’ll see the link of RegexLib. Copy the expression and paste it into RegularExpress(“”) attribute.
  1. [RegularExpression("^[0-9+]{5}-[0-9+]{7}-[0-9]{1}$")]  
  2. public string Cnic { get; set; }  
Now if you want to set the value that the value of this field should be a max from one value and minimum from another value, then you
can define Range attribute.
  1. [Range(18, 25)]  
  2. public string Age { get; set; }  
Now if you’re thinking about how you can set its custom ErrorMessage then put a comma after 25 and you’ll see intellisense and you can do it on your own.
Maybe you’re working on a form which has address field or name field and here you want to limit the text field's size value, then you need to provide the StringLength attribute on the top of the field.
  1. [StringLength(30)]  
  2. public string Name { get; set; }  
Here in the scenario, you’ll see the maximum value in the intellisense but you want to initialize the minimum value here, then
  1. [StringLength(30, MinimumLength = 3)]  
  2. public string Name { get; set; }  
As you already know that DateTime data type of C# has a huge amount of information about Date and Time but if you want to just accept the Date then,
  1. [DataType(DataType.Date)]  
  2. public DateTime? DateOfBirth { get; set; }  
And finally, after complete decoration of our ‘Student’ class, our class looks like,

  1. public class Student {  
  2.     [Required(ErrorMessage = "Please Enter Name e.g. John Doe")]  
  3.     [StringLength(30, MinimumLength = 3)]  
  4.     public string Name {  
  5.         get;  
  6.         set;  
  7.     }  
  8.     [Required]  
  9.     [EmailAddress]  
  10.     public string Email {  
  11.         get;  
  12.         set;  
  13.     }  
  14.     [Required]  
  15.     [Compare("Email")]  
  16.     public string RetypeEmail {  
  17.         get;  
  18.         set;  
  19.     }  
  20.     [DisplayName("Phone Number")]  
  21.     public string Phone {  
  22.         get;  
  23.         set;  
  24.     }  
  25.     [RegularExpression("^[0-9+]{5}-[0-9+]{7}-[0-9]{1}$")]  
  26.     [Required]  
  27.     public string Cnic {  
  28.         get;  
  29.         set;  
  30.     }  
  31.     [Range(18, 25)]  
  32.     public string Age {  
  33.         get;  
  34.         set;  
  35.     }  
  36.     [StringLength(35)]  
  37.     public string City {  
  38.         get;  
  39.         set;  
  40.     }  
  41.     public string Address {  
  42.         get;  
  43.         set;  
  44.     }  
  45.     [Required]  
  46.     [DataType(DataType.Date)]  
  47.     public DateTime ? DateOfBirth {  
  48.         get;  
  49.         set;  
  50.     }  
  51. }  
We’ll use this class in our articles.
Last Words
These are not all the Data Annotation Attributes, but they are enough to start for the development and they are necessary for the developers to know. Find your problems’ solution on Google your own, and make your search better. Search for the solution to your problem in the form of keywords. Try to understand the intellisense and be a good programmer.

Similar Articles