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.
- public class Student {
- private string _StudentName;
- public string StudentName {
- get {
- return _StudentName;
- }
- set {
- if (value == null) {
- throw new
- NullReferenceException("The value should not Null");
- }
- _StudentName = value;
- }
- }
- }
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.
- namespace ValidationDemo.Models {
- public class Student {
- public string Name {
- get;
- set;
- }
- public string Email {
- get;
- set;
- }
- public string RetypeEmail {
- get;
- set;
- }
- public string Cnic {
- get;
- set;
- }
- public int Age {
- get;
- set;
- }
- public string City {
- get;
- set;
- }
- public DateTime ? DateOfBirth {
- get;
- set;
- }
- }
- }
I’ve decorated the model class with these fields.
Required
Required attribute is used to make the fields required.
- [Required]
- public string Name {
- get;
- set;
- }
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.
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.
- [Required] public string Name {
- get;
- set;
- }[Required(ErrorMessage = "Please Enter Valid Email Address")]
- public string Email
- {
- get;
- set;
- }
EmailAddress
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:
- [EmailAddress]
- public string Email { get; set; }
Might be you’ve even seen it this way:
- [DataType(DataType.EmailAddress)]
- public string Email { get; set; }
This is actually the old way, now you can write it directly as I did in the first technique.
Compare
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.
- [Required(ErrorMessage = "Please Enter Valid Email Address")]
- public string Email { get; set; }
-
- [Compare("Email")]
- 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.
- [Required]
- [Compare("Email")]
- public string RetypeEmail { get; set; }
But some developers don’t like this way and they prefer this:
- [Compare("Email"), Required]
- public string RetypeEmail { get; set; }
RegularExpression
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.
- [RegularExpression("^[0-9+]{5}-[0-9+]{7}-[0-9]{1}$")]
- public string Cnic { get; set; }
Range
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.
- [Range(18, 25)]
- 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.
StringLength
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.
- [StringLength(30)]
- 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
- [StringLength(30, MinimumLength = 3)]
- public string Name { get; set; }
Date
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,
- [DataType(DataType.Date)]
- public DateTime? DateOfBirth { get; set; }
And finally, after complete decoration of our ‘Student’ class, our class looks like,
- public class Student {
- [Required(ErrorMessage = "Please Enter Name e.g. John Doe")]
- [StringLength(30, MinimumLength = 3)]
- public string Name {
- get;
- set;
- }
- [Required]
- [EmailAddress]
- public string Email {
- get;
- set;
- }
- [Required]
- [Compare("Email")]
- public string RetypeEmail {
- get;
- set;
- }
- [DisplayName("Phone Number")]
- public string Phone {
- get;
- set;
- }
- [RegularExpression("^[0-9+]{5}-[0-9+]{7}-[0-9]{1}$")]
- [Required]
- public string Cnic {
- get;
- set;
- }
- [Range(18, 25)]
- public string Age {
- get;
- set;
- }
- [StringLength(35)]
- public string City {
- get;
- set;
- }
- public string Address {
- get;
- set;
- }
- [Required]
- [DataType(DataType.Date)]
- public DateTime ? DateOfBirth {
- get;
- set;
- }
- }
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.