Data Annotations is a Library in .NET Framework which resides in Assembly System.ComponentModel.DataAnnotations.
DataAnnotations contains Validation Attributes to enforce the validation rules..
Introduction
In this Article we will see how we can use Data Annotations to Perform Validations in MVC 5 Application.We can easily add validations to our Application using DataAnnotations to our Model classes.They allow us to define rules which we want to apply for our model properties
The Data annotation attributes are of three categories:Validation attributes,display attributes,and data modelling attributes..we can see the brief Explanation from
here...
Objective
In any database driven Applications validating the user input data is mandatory for us.we have to validate all the data given by user to ensure that all the data entered was valid which belongs to the datatype and length values of the respective fields..
In MVC Applications we have to validate the Model classes before the database hits.Usually, we use to Validate them by providing server side code which is performance drawback and not a good idea to validate all the fields data individually.By using the Data Annotations attributes we can get rid of it as it take cares of both client side and server side validations itself.
Let us now see how to use DataAnnotations with a Model class
Step 1 : Let us create a single table Database name Students which contains the information of students..
Here we are going to Validate the Student Name and Student Marks..Now lets create a MVC Application
Please have a look previous article on MVC App
hereUsing the code
Open the Students class from Models Folder and write the attributes to each and every property as shown
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
namespace MVCStudents.Models
{
public class Students
{
public int Id { get; set; }
[Required]
[StringLength(50, MinimumLength = 5)]
public string studentname { get; set; }
[Required]
[Range(1, 200)]
public int studentmarks { get; set; }
[Required]
[Range(1, 1200)]
public int Test { get; set; }
}
public class StudentsDbcontext : DbContext
{
public DbSet<Students> Students { get; set; }
}
}
In the above code snippet Required attribute is used in each property.In the name property string length attribute indicates the minimum and maximum length of the attribute.In the Marks and Text property range attribute indicates the Maximum and Minimum length...
Now we can see the Following Page with Validation Messages when you try to enter data into the Fields
Here we looked into Required Validator like the same way we can use different Validators like Regular Expression ,Key Attribute,Display Attribute
Conclusion.
In this Article we have learned how to provide validations in MVC5 Application using Data Annotations.Thanks for reading my article
Reference