27
DecMVC Data Annotations for Model Validation
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
- DataType
Specify the datatype of a property
Syntax
[DataType(DataType.Text)]
- DisplayName
specifies the display name for a property.
Syntax
[Display(Name="Student Name")]
- DisplayFormat
specify the display format for a property like a different format for a Date property.
Syntax
[DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}")]
- Required
Specify a property as required.
Syntax
[Required(ErrorMessage="Please enter name"),MaxLength(30)]
- 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.")]
- Range
validates the value of a property within a specified range of values.
Syntax
[Range(100,500,ErrorMessage="Please enter correct value")]
- StringLength
specifies the min and max length for a string property.
Syntax
[StringLength(30,ErrorMessage="Do not enter more than 30 characters")]
- MaxLength
specifies the max length for a string property.
Syntax
[MaxLength(3)]
- Bind
Specify fields to include or exclude when adding parameter or form values to model properties.
Syntax
[Bind(Exclude = "StudentID")]
- ScaffoldColumn
specifies fields for hiding from editor forms.
How to use Data Annotation Validators
- 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.
- 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; } }
- 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.
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..!