Data Annotations in ASP.NET MVC

Data Annotation Attributes in ASP.NET MVC

In this article, I am going to give you a brief introduction into Data Annotation Attributes in ASP.NET MVC Application which is used for validating the data of a model.

Now a day’s, it’s a challenging job for a web developer to validate the user input for any Web application. As a web developer, we not only validate the business logic at the client side that is in the browser, but also we need to validate the business logic running on the Server. That means as a developer we need to validate the business logic both at the client side as well as server side.

The client-side validation of the business logic gives the users immediate feedback on the information they entered into a web page and which is an expected feature in today’s web applications. Along the same line, the server side validation logic is in place because we never trust the information coming from the network. 

What are the Validations?

In simple term, we can say that validations are nothing but some rules set by the developer on the input fields of a web page so as to satisfy the business rules for that particular input field in order have to maintain the proper data in a system.

There are two types of validations:

  1. Server-side Validations
  2. Client Side Validations

While doing validations, as a developer we need to take care of not only the proper validation but also ensure that the validation meets the business rule as per the requirement. From the security point of view, it is also possible that some hackers may bypass client-side validation and insert some vulnerable data to the server.

When we talk about the validation in ASP.NET MVC framework, we primarily focus on validating the model value. That means has the user provided a required value? Is the value in the required range? Is the value in a proper format etc.?

In ASP.NET MVC web applications, we can do the following three types of validations:
  1. HTML validation / JavaScript validation (i.e. Client-Side Validation)
  2. ASP.NET MVC Model validation (i.e. Server-side Validation)
  3. Database validation (i.e. Server-side Validation)

Among the above three, the most secure validation is the ASP.NET MVC model validation. In HTML/JavaScript validation, the validation can break easily by disabling the javascript in the client machine, but the model validation can’t break.

ASP.NET MVC Framework provides a concept called Data Annotation which is used for model validation. It’s inherited from System.ComponentModel.DataAnnotations assembly.

That means ASP.NET MVC Framework uses Data Annotation attributes to implement model validations. The Data Annotation Attributes includes built-in validation attributes for different validation rules, which can be applied to the model class properties.

The ASP.NET MVC framework will automatically enforce the validation rules and then display proper validation messages in the view if validation fails.

The System.ComponentModel.DataAnnotations assembly has many built-in validation attributes, for example:
  1. Required
  2. Range
  3. RegularExpression,
  4. Compare
  5. StringLength
  6. Data type

Along with the above build-in validation attributes, there are also many data types the user can select to validate the input. Using this data type attribute, the user can validate for the exact data type as in the following:

  1. Credit Card number
  2. Currency
  3. Custom
  4. Date
  5. DateTime
  6. Duration
  7. Email Address
  8. HTML
  9. Image URL
  10. Multiline text
  11. Password
  12. Phone number
  13. Postal Code
  14. Upload
Let’s create an empty ASP.NET MVC application with the name DataAnnotationInMVC.

Open Visual Studio and create a new project

Select File => New => Project as shown below

Data Annotation Attributes in ASP.NET MVC Application

After clicking on “Project” link a new dialog will pop up.

In that we are going to select web templates from the left pane after selecting web template, select “ASP.NET Web Application” as shown below.

Data Annotation Attributes in ASP.NET MVC Application - Project

After selecting this project template next we are going to name the project as “DataAnnotationInMVC” and clicking on the OK button a new dialog will pop up with Name “New ASP.NET Project” for selecting project Templates.

Data Annotation Attributes in ASP.NET MVC Application

In this dialog, we are going to choose MVC project template and then we are going to choose Authentication type for doing that just click on Change Authentication button, a new dialog will pop up with a name “Change Authentication” here we are going to choose No Authentication click on OK Button.

It will take some to time create the project for us. Once the project is created let’s see the folder structure as shown below

Data Annotation Attributes in ASP.NET MVC Application - Folder Structore

Next, add Employee.cs file to the Models Folder and copy paste the following code
namespace DataAnnotationInMVC.Models
{
    public class Employee
    {
        public Guid EmployeeId
        {
            get;
            set;
        }
        public string FirstName
        {
            get;
            set;
        }
        public string LastName
        {
            get;
            set;
        }
    public int Age
    {
      get;
      set;
    }
        public DateTime DateOfBirth
        {
            get;
            set;
        }
        public string Address
        {
            get;
            set;
        }
        public string Mobile
        {
            get;
            set;
        }
        
        public string PostalCode
        {
            get;
            set;
        }

        public string EmailId
        {
            get;
            set;
        }
        
        public string UserName
        {
            get;
            set;
        }
        public string Password
        {
            get;
            set;
        }
        public string ConfirmPassword
        {
            get;
            set;
        }
        public string URL
        {
            get;
            set;
        }
    }
}
Now Add EmployeeContoller to the Controllers Folder and copy paste the following code
using DataAnnotationInMVC.Models;
namespace DataAnnotationInMVC.Controllers
{
    public class EmployeeController : Controller
    { 
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult Create()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Create(Employee employee)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    return RedirectToAction("Index");
                }
                return View();
            }
            catch
            {
                return View();
            }
        }
    }
}
Next, create the Create.cshtml view

Right-click on the Create action method of Home Controller class from the context menu and click on Add View. Once you click on the Add View option then it will show you the below popup.

Data Annotation Attributes in ASP.NET MVC Application - View

Then click on Add button which will create the Create.cshtml view in Home Folder which is inside Views folder.

Copy and paste the following code in the Create.cshtml view

@model DataAnnotationInMVC.Models.Employee

@{
    ViewBag.Title = "Create Employee";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Create Employee</h2>

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        <hr/>
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Age, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Age, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Age, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.DateOfBirth, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.DateOfBirth, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.DateOfBirth, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Mobile, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Mobile, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Mobile, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.PostalCode, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.PostalCode, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.PostalCode, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.EmailId, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.EmailId, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.EmailId, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.UserName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.UserName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.UserName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.ConfirmPassword, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.ConfirmPassword, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.ConfirmPassword, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.URL, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.URL, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.URL, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-danger" />
            </div>
        </div>
    </div>
}

We have added Create.cshtml view to create the Action Method when we run the application and go to the “/Employee/Create” URL it will look as shown below:

Data Annotation Attributes in ASP.NET MVC Application

The Validation attributes in ASP.NET MVC Framework provides both the client side and server side validation. There are 2 simple steps to enable client side validation in ASP.NET MVC application.

In the First step, we need to Enable ClientValidation and UnobtrusiveJavaScript in the web.config file as shown below.
<appSettings> 
  <add key="ClientValidationEnabled" value="true" />
  <add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>

In the second step, we need to include the references to the following javascript files.

Add the following javascript files in sequence in the _Layout.cshtml view which is inside the shared folder as our create.cshtml view uses _Layout.cshtml view

<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>

In real time we need to include the references to the javascript files in the master page which avoids the need to reference them on each and every view where we need the validation. The order in which the script files are referenced is also important. jquery.validate is dependent on jquery and /jquery.validate.unobtrusive is dependent on jquery.validate, so they should be referenced in the above order. Otherwise, client side validation will not work as expected. In short, JavaScript is parsed “top-down”, so all dependencies need to be referenced before the dependent reference.

With the above 2 changes, validation should now happen on the client side without a round trip to the server. If the client disables javascript in the browser, then client-side validation does not work, but the server side validation will continue to work as expected. 

In the next article, I will discuss the Required and StringLength attributes in ASP.NET MVC application with real-time examples.

SUMMARY

In this article, I try to explain the basics of Data Annotation Attributes in ASP.NET MVC application step by step. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article. 

Leave a Reply

Your email address will not be published. Required fields are marked *