Model Validation Using Data Annotations In ASP.NET MVC

Before this I would request you to go through previous articles on ASP.NET MVC:

I hope the above articles are clear. So we will move ahead and get hands on with Data Annotations in ASP.NET MVC.

Data Annotations are nothing but certain validations that we put in our models to validate the input from the user. ASP.NET MVC provides a unique feature in which we can validate the models using the Data Annotation attribute. Import the following namespace to use data annotations in the application.

System.ComponentModel.DataAnnotations

It is very easy to use and the code becomes much cleaner as compared to normal ASP.NET validators.
Let us understand some of the validator attributes that we can use in MVC.

Types of Data Annotations in ASP.NET MVC

Required

This attribute specifies that the value is mandatory and cannot be skipped.

Syntax

[Required(ErrorMessage="Please enter name"),MaxLength(30)]

DataType

This attribute is used to specify the datatype of the model.

Syntax

[DataType(DataType.Text)]

Range

Using this attribute we can set a range between two numbers.

Syntax

[Range(100,500,ErrorMessage="Please enter correct value")]

StringLength

Using this attribute we can specify maximum and minimum length of the property.

Syntax

[StringLength(30,ErrorMessage="Do not enter more than 30 characters")]

DisplayName

Using this attribute we can specify property name to be displayed on view.

Syntax

[Display(Name="Student Name")]

MaxLength

Using this attribute we can specify maximum length of property.

Syntax

[MaxLength(3)]

Bind

This attribute specify fields to include or exclude for model binding.

Syntax

[Bind(Exclude = "StudentID")]

DisplayFormat

This attribute allows us to set date in the format specified as per the attribute.

Syntax

[DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}")]

RegularExpression

We can set a regex pattern for the property. For ex: Email ID.

Syntax

[RegularExpression(@"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$", ErrorMessage = "Email is not valid.")]

Creating MVC Application


Let us implement these in a sample application. Open Visual Studio. Go to File->New->Project. Give a suitable name to the application. Click OK.



Select MVC Template. Click OK.



Adding Model to Application.

Let us create a model in the Models folder. I have named it Student.



Add the following properties to it.

  1. public class Student  
  2.   
  3.    [ScaffoldColumn(false)]  
  4.    publicintStudentID { getset; }  
  5.    [DataType(DataType.Text)]  
  6.    [Required(ErrorMessage = "Please enter name"), MaxLength(30)]  
  7.    [Display(Name = "Student Name")]  

  8.    public string Name { getset; }  
  9.    [MaxLength(3),MinLength(1)]  
  10.    [Required(ErrorMessage = "Please enter marks")]  

  11.    publicint Marks { getset; }  
  12.    [DataType(DataType.EmailAddress)]  
  13.    [Required(ErrorMessage = "Please enter Email ID")]  
  14.    [RegularExpression(@"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$", ErrorMessage = "Email is not valid.")]  

  15.    public string Email { getset; }  
  16.    [Required(ErrorMessage = "Please enter department")]  

  17.    public string Department { getset; }  
  18.    [Required(ErrorMessage = "Please enter Mobile No")]  
  19.    [Display(Name = "Contact Number")]  
  20.    [DataType(DataType.PhoneNumber)]  
  21.    public int Mobile { getset; }  
  22. }
Let us create a context class now. Add the following method in the class.
  1. public class StudentsDbcontext : DbContext  
  2. {  
  3.    publicDbSet<Student> Students { getset; }  
  4. }  
To import DbContext we need to include using System.Data.Entity namespace in the application.

So our final model is complete,



Adding Controller

Let us add controller. Right click on Controller. Add->Controller.



Select MVC 5 Empty Controller. Click Add. I have named it Student.



We have the following method in controller.
  1. publicActionResult Index()  
  2. {  
  3.   
  4.    return View();  
  5. }  
Adding View

Let us add a view for this ActionResult. Right click on Index() method. Go to Add->View. Select the Create template as we wish to create an input form. We will select Student as Model Class as we have created this model and finally we need to select our context class that we have created along with our model. Click Add.



We should get a view view the following markup.
  1. @modelDataAnnotations.Models.Student  
  2.    
  3. @{  
  4.     ViewBag.Title = "Index";  
  5. }  
  6.    
  7.    
  8. <h2>Using Data Annotations</h2>  
  9.    
  10.    
  11. @using (Html.BeginForm())   
  12. {  
  13.     @Html.AntiForgeryToken()  
  14.       
  15.     <div class="form-horizontal">  
  16.         <h4></h4>  
  17.         <hr />  
  18.         @Html.ValidationSummary(true""new { @class = "text-danger" })  
  19.         <div class="form-group">  
  20.             @Html.LabelFor(model =>model.Name, htmlAttributes: new { @class = "control-label col-md-2" })  
  21.             <div class="col-md-10">  
  22.                 @Html.EditorFor(model =>model.Name, new { htmlAttributes = new { @class = "form-control" } })  
  23.                 @Html.ValidationMessageFor(model =>model.Name, ""new { @class = "text-danger" })  
  24.             </div>  
  25.         </div>  
  26.    
  27.         <div class="form-group">  
  28.             @Html.LabelFor(model =>model.Marks, htmlAttributes: new { @class = "control-label col-md-2" })  
  29.             <div class="col-md-10">  
  30.                 @Html.EditorFor(model =>model.Marks, new { htmlAttributes = new { @class = "form-control" } })  
  31.                 @Html.ValidationMessageFor(model =>model.Marks, ""new { @class = "text-danger" })  
  32.             </div>  
  33.         </div>  
  34.    
  35.         <div class="form-group">  
  36.             @Html.LabelFor(model =>model.Email, htmlAttributes: new { @class = "control-label col-md-2" })  
  37.             <div class="col-md-10">  
  38.                 @Html.EditorFor(model =>model.Email, new { htmlAttributes = new { @class = "form-control" } })  
  39.                 @Html.ValidationMessageFor(model =>model.Email, ""new { @class = "text-danger" })  
  40.             </div>  
  41.         </div>  
  42.    
  43.         <div class="form-group">  
  44.             @Html.LabelFor(model =>model.Department, htmlAttributes: new { @class = "control-label col-md-2" })  
  45.             <div class="col-md-10">  
  46.                 @Html.EditorFor(model =>model.Department, new { htmlAttributes = new { @class = "form-control" } })  
  47.                 @Html.ValidationMessageFor(model =>model.Department, ""new { @class = "text-danger" })  
  48.             </div>  
  49.         </div>  
  50.    
  51.         <div class="form-group">  
  52.             @Html.LabelFor(model =>model.Mobile, htmlAttributes: new { @class = "control-label col-md-2" })  
  53.             <div class="col-md-10">  
  54.                 @Html.EditorFor(model =>model.Mobile, new { htmlAttributes = new { @class = "form-control" } })  
  55.                 @Html.ValidationMessageFor(model =>model.Mobile, ""new { @class = "text-danger" })  
  56.             </div>  
  57.         </div>  
  58.    
  59.         <div class="form-group">  
  60.             <div class="col-md-offset-2 col-md-10">  
  61.                 <input type="submit" value="Create" class="btnbtn-primary" />  
  62.             </div>  
  63.         </div>  
  64.     </div>  
  65. }  
  66.    
  67. <div>  
  68.     @Html.ActionLink("Back to List""Index")  
  69. </div>  
  70.    
  71. @sectionScripts {  
  72.     @Scripts.Render("~/bundles/jqueryval")  
  73. }  
Browse the Application

Let us now run the application and check if validations are working.



So we have validations working perfectly. Further we will be validating our model to test other specified validations also.



Summary

So we have successfully implemented Data annotations in ASP.NET MVC application. I hope this post is useful to developers.

 

Up Next
    Ebook Download
    View all
    Learn
    View all