Year End Sale: Get Upto 40% OFF on Live Training! Offer Ending in
D
H
M
S
Get Now
MVC Data Annotations for Model Validation

MVC Data Annotations for Model Validation

31 Mar 2024
Intermediate
29.4K Views
11 min read
Learn with an interactive course and practical hands-on labs

ASP.NET MVC with Web API Foundations Course - Free

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

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

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

 To indicate that it should be validated
Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at ScholarHat)

Shailendra Chauhan, Founder and CEO of ScholarHat by DotNetTricks, is a renowned expert in System Design, Software Architecture, Azure Cloud, .NET, Angular, React, Node.js, Microservices, DevOps, and Cross-Platform Mobile App Development. His skill set extends into emerging fields like Data Science, Python, Azure AI/ML, and Generative AI, making him a well-rounded expert who bridges traditional development frameworks with cutting-edge advancements. Recognized as a Microsoft Most Valuable Professional (MVP) for an impressive 9 consecutive years (2016–2024), he has consistently demonstrated excellence in delivering impactful solutions and inspiring learners.

Shailendra’s unique, hands-on training programs and bestselling books have empowered thousands of professionals to excel in their careers and crack tough interviews. A visionary leader, he continues to revolutionize technology education with his innovative approach.
Accept cookies & close this