---
title: "What is validation in MVC?"  
description: "What is validation in MVC?"  
author: "Anonymous User"  
published: 2020-01-27  
updated: 2020-01-27  
canonical: https://www.mindstick.com/forum/155738/what-is-validation-in-mvc  
category: "asp.net mvc"  
tags: ["asp.net mvc"]  
reading_time: 5 minutes  

---

# What is validation in MVC?

Please [briefly explain](https://www.mindstick.com/forum/156854/briefly-explain-the-concept-of-constructor-overloading) me about [validation in MVC](https://www.mindstick.com/forum/34733/how-can-use-validation-in-mvc) with example and also with suitable image.

## Replies

### Reply by Nishi Tiwari

In the web applications, domain [validation](https://www.mindstick.com/articles/12234/validation-using-data-annotation-using-entity-framework) plays an important role in the application. Data entered from the client’s side may not always be correct. Therefore we need to ensure that the data entered by the user is not only validated but it is also correct application-logic wise.

In the ASP.NET Model validations three type of validations we can perform:

1. HTML validation / JavaScript validation

2. ASP.NET [MVC](https://www.mindstick.com/forum/155803/define-cache-profile-in-mvc) Model validation

3. Database validation

But the above all most secure validation is the ASP.NET MVC model validation. In HTML/JavaScript, the validation can be break easily, but the model validation cannot. In ASP.NET MVC model validations are done using Data Annotation and it is inherited from System.ComponentModel.DataAnnotations assembly.

We can also say that for any website, there are many input fields. Users can enter the data in those input fields. Now these input fields are exposed to the client browser. Users may enter anything they wants to the input fields. If the user may enters some wrong data then you will have some irrelevant or wrong data with your database also. In this way, providing the authority to the user to enter data in input fields which we will be inserting into the database and which will be used for many purposes can cause security holes in to the system if we don't put any restrictions on the input fields.

In simple words we can say that **[validations are rules set by the developer](https://www.mindstick.com/forum/155739/define-viewbag-in-mvc)** on input fields so as to satisfy the business rules for those particular input field in which they have the proper data in the system.

## There are two types of validations:

1. Server side Validations

2. Client Side Validations

While performing validations we must need to take care of not only the proper validation, but also ensure the validation meets the business rule as per the requirement. This also reduces the amount of code we need to write and makes the code to write less error prone and easier to maintain.

ASP.NET MVC framework provides the built-in annotations which we can apply on Model properties. It validates input first and then display appropriate message to the user.

## Commonly used Validation Annotations

Required:- It is used to make a required field.

DisplayName:- It is used to define those text which we want to display for the fields.

StringLength:- It defines a maximum length for a string field which is needed.

Range:- It is used to set a maximum and minimum value for a numeric field.

## Example

Create an example which will validate input by using the annotations. We are creating a StudentsController and then a Student Model.

**Controller**\

```
// StudentsController.cs 1.	using System;
2.	using System.Collections.Generic;
3.	using System.Linq;
4.	using System.Web;
5.	using System.Web.Mvc;
6.	namespace MvcApplicationDemo.Controllers
7.	{
8.	    public class StudentsController : Controller
9.	    {
10.	        // GET: Students
11.	        public ActionResult Index()
12.	        {
13.	            return View();
14.	        }
15.	    }
16.	}
```

## Model

```
// Student.cs
1.	using System.ComponentModel.DataAnnotations;
2.
3.	namespace MvcApplicationDemo.Models
4.	{
5.	    public class Student
6.	    {
7.	        public int ID { get; set; }
8.	        // -- Validating Student Name
9.	        [Required(ErrorMessage ="Name is required")]
10.	        [MaxLength(12)]
11.	        public string Name { get; set; }
12.	        // -- Validating Email Address
13.	        [Required(ErrorMessage ="Email is required")]
14.	        [EmailAddress(ErrorMessage = "Invalid Email Address")]
15.	        public string Email { get; set; }
16.	        // -- Validating Contact Number
17.	        [Required(ErrorMessage = "Contact is required")]
18.	        [DataType(DataType.PhoneNumber)]
19.	        [RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Not a valid Phone number")]
20.	        public string Contact { get; set; }
21.	    }
22.	}
```

**View** \

```
// Index.cshtml
1.	@model MvcApplicationDemo.Models.Student
2.	@{
3.	    ViewBag.Title = "Index";
4.	}
5.	<h2>Index</h2>
6.	@using (Html.BeginForm())
7.	{
8.	    @Html.AntiForgeryToken()
9.	    <div class="form-horizontal">
10.	        <h4>Student</h4>
11.	        <hr />
12.	        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
13.	        <div class="form-group">
14.	            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
15.	            <div class="col-md-10">
16.	                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
17.	                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
18.	            </div>
19.	        </div>
20.	        <div class="form-group">
21.	            @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
22.	            <div class="col-md-10">
23.	                @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
24.	                @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
25.	            </div>
26.	        </div>
27.	        <div class="form-group">
28.	            @Html.LabelFor(model => model.Contact, htmlAttributes: new { @class = "control-label col-md-2" })
29.	            <div class="col-md-10">
30.	                @Html.EditorFor(model => model.Contact, new { htmlAttributes = new { @class = "form-control" } })
31.	                @Html.ValidationMessageFor(model => model.Contact, "", new { @class = "text-danger" })
32.	            </div>
33.	        </div>
34.	        <div class="form-group">
35.	            <div class="col-md-offset-2 col-md-10">
36.	                <input type="submit" value="Create" class="btn btn-default" />
37.	            </div>
38.	        </div>
39.	    </div>
40.	}
41.	<div>
42.	    @Html.ActionLink("Back to List", "Index")
43.	</div>
44.	@section Scripts {
45.	    @Scripts.Render("~/bundles/jqueryval")
46.	}
```

## Output:

To see an output, right click on the Index.cshtml file and select view in browser. This will produce the following output.

![What is validation in MVC?](https://www.mindstick.com/mindstickforums/d6889437-e043-4da7-8e2a-2877e2959aac/images/b731a874-683c-4860-8178-567edaf2e0ea.png)\

![What is validation in MVC?](https://www.mindstick.com/mindstickforums/d6889437-e043-4da7-8e2a-2877e2959aac/images/3bf4ef64-cdb3-46f6-b978-41e892a46e6d.png)\


---

Original Source: https://www.mindstick.com/forum/155738/what-is-validation-in-mvc

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
