Browse Tutorials

02 Intermediate

MVC Data Annotations for Model Validation

MVC Data Annotations for Model Validation

31 Mar 2024
Intermediate
25.7K Views
11 min read

MVC Data Annotations: An Overview

In this MVC Tutorial, we are going to explore Data Annotations. Data validation is a key aspect of developing web applications. In Asp.Net MVC, we can easily apply validation to web applications by using Data Annotation attribute classes to model classes. Data Annotation attribute classes are present in the System.ComponentModel.DataAnnotations namespace and are available to Asp.Net projects like Asp.Net web application & website, Asp.net MVC, Web forms, and also to Entity Framework models.

Data Annotations help us to define the rules for the model classes or properties for data validation and display suitable messages to end users.

Read More: MVC Interview Questions and Answers

Data Annotation Validator Attributes

  1. DataType

    Specify the datatype of a property

    Syntax

    
    [DataType(DataType.Text)]
    

  2. DisplayName

    specifies the display name for a property.

    Syntax

    
    [Display(Name="Student Name")]
    

  3. DisplayFormat

    specify the display format for a property like a different format for a Date property.

    Syntax

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

  4. Required

    Specify a property as required.

    Syntax

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

  5. Regular expression

    validates the value of a property by a specified regular expression pattern.

    Syntax

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

  6. Range

    validates the value of a property within a specified range of values.

    Syntax

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

  7. StringLength

    specifies the min and max length for a string property.

    Syntax

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

  8. MaxLength

    specifies the max length for a string property.

    Syntax

    
    [MaxLength(3)]
    

  9. Bind

    Specify fields to include or exclude when adding parameter or form values to model properties.

    Syntax

    
    [Bind(Exclude = "StudentID")]
    

  10. ScaffoldColumn

    specifies fields for hiding from editor forms.

How to use Data Annotation Validators

  1. Add Required Assembly

    You need the necessary assembly referenced in your project to use Data Annotation validators. The System.ComponentModel.DataAnnotations namespace contains the validation attributes you'll use.

  2. Apply Validation Attributes to Model Properties

    Decorate your model properties with Data Annotation validation attributes to specify validation rules. Some of the validation attributes include [Required], [StringLength], [Range], [EmailAddress], [RegularExpression], etc.

    Example

    
    using System.ComponentModel.DataAnnotations;
    
    public class MyModel
    {
        [Required(ErrorMessage = "The Name field is required.")]
        public string Name { get; set; }
    
        [StringLength(50, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 5)]
        public string Description { get; set; }
    
        [Range(18, 100, ErrorMessage = "The Age must be between {1} and {2}.")]
        public int Age { get; set; }
    
        [EmailAddress(ErrorMessage = "Invalid email address.")]
        public string Email { get; set; }
    
        [RegularExpression(@"^\d{5}(-\d{4})?$", ErrorMessage = "Invalid ZIP code.")]
        public string ZipCode { get; set; }
    }
    
  3. Display Validation Error Messages in Views

    In your view, use the ValidationMessageFor HTML helper to display validation error messages associated with model properties.

    Example

    
    <div class="form-group">
        @Html.LabelFor(model => model.Name)
        @Html.TextBoxFor(model => model.Name, new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
    </div>
    

    The ValidationMessageFor helper will automatically display the error message specified in the Data Annotation attribute if validation fails.

  4. With these configurations in place, Data Annotation validators will validate your model properties both on the client and server side.

Designing the Model with Data Annotations


using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
namespace Employee.Models
{
 [Bind(Exclude = "EmpId")]
 public class Employee
 {
 [ScaffoldColumn(false)]
 public int EmpId { get; set; }
 
 [DisplayName("Employee Name")]
 [Required(ErrorMessage = "Employee Name is required")]
 [StringLength(100,MinimumLength=3)]
 public String EmpName { get; set; } 
 
 [Required(ErrorMessage = "Employee Address is required")] 
 [StringLength(300)]
 public string Address { get; set; } 
 
 [Required(ErrorMessage = "Salary is required")] 
 [Range(3000, 10000000,ErrorMessage = "Salary must be between 3000 and 10000000")]
 public int Salary{ get; set; } 
 
 [Required(ErrorMessage = "Please enter your email address")] 
 [DataType(DataType.EmailAddress)]
 [Display(Name = "Email address")]
 [MaxLength(50)]
 [RegularExpression(@"[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}", ErrorMessage = "Please enter correct email")]
 public string Email { get; set; }
 }
}

Once we have defined validation to the model by using data annotations, these are automatically used by HTML Helpers in views. For client-side validation to work, please ensure that below two <SCRIPT> tag references are in the view.

 <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> 
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script> 

Presenting the Model in the View

 @model Employee.Models
@{ 
 ViewBag.Title = "Employee Details"; 
 Layout = "~/Views/Shared/_Layout.cshtml";
 }
 @using (Html.BeginForm())
 {
 <div class="editor-label">
 @Html.LabelFor(m => m.EmpName)
 </div>
 <div class="editor-field"> 
 @Html.TextBoxFor(m => m.EmpName) 
 @Html.ValidationMessageFor(m => m.EmpName)
 </div> 
 <div class="editor-label">
 @Html.LabelFor(m => m.Address)
 </div> 
 <div class="editor-field">
 @Html.TextBoxFor(m => m.Address) 
 @Html.ValidationMessageFor(m => m.Address)
 </div> 
 <div class="editor-label"> 
 @Html.LabelFor(m => m.Salary)
 </div> 
 <div class="editor-field"> 
 @Html.TextBoxFor(m => m.Salary) 
 @Html.ValidationMessageFor(m => m.Salary)
 </div> 
 <div class="editor-label">
 @Html.LabelFor(m => m.Email)
 </div> 
 <div class="editor-field"> 
 @Html.TextBoxFor(m => m.Email) 
 @Html.ValidationMessageFor(m => m.Email)
 </div> 
 <p> <input type="submit" value="Save" />
 </p>
} 
Summary

In this article, I try to expose the Data Annotations with examples. I hope you will refer to this article for your needs. I would like to have feedback from my blog readers. Please post your feedback, questions, or comments about this article. Enjoy Coding..!

Unlock the next level of MVC:

FAQs

Q1. Can we do validation in MVC using data annotations?

Yes we can easily apply validation to web application by using Data Annotation attribute classes to model class

Q2. Which attributes can be used for data validation in MVC?

Data Annotation is used for data validation for developing web-based applications. We can quickly apply validation with the help of data annotation attribute

Q3. Why do we use @valid annotation?

 To indicate that it should be validated
Share Article
Batches Schedule
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this