Table of contents
1.
Introduction
2.
ASP.NET MVC Input Validation
2.1.
The Base Validator Class
2.2.
Commonly Used Validation Annotations
2.3.
DRY Principle
3.
Understanding MVC Validation with an Example
3.1.
Controller
3.2.
Model
3.3.
View
3.4.
Output
4.
Frequently Asked Questions
5.
Key Takeaways
Last Updated: Mar 27, 2024

ASP.NET MVC Validations

Author Naman Kukreja
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

On the internet, whenever you sign in on any website or fill in the details, you see some remarks like "the password entered is incorrect", " this field is required".

So what are all these statements?

These statements come from validations that the programmer has set so that any unidentified user cannot access the content. While moving further in the blog, we will learn more about this.

So without wasting any time further, let's dive into our topic.

ASP.NET MVC Input Validation

Validation is the process of checking and verifying the user's details and redirecting him accordingly. This is an essential task for the programmer. 

The application must allow only valid users to access the content, checking their entered information.

ASP.NET provides some inbuilt annotations that users can apply to model properties.

The Base Validator Class

There are many validators in ASP.NET, and all of them inherit the methods and properties of the base class validators. Here are the methods and the properties of the base validator class:

  1. ControlToValidate: It indicates the input control to validate. This is a mandatory attribute. It must be unique.
  2. Text: It holds the message to be displayed in case of failure.
  3. Enabled: It disables or enables the validator.
  4. IsValid: The boolean attribute indicates whether the control is valid or not.
  5. Validate(): This method updates the IsValid and revalidates the control.

Commonly Used Validation Annotations

These are some commonly used annotations with their explanation:

DRY Principle

One of the core design principles of ASP.NET MVC is DRY, which stands for Don’t Repeat Yourself. It is mainly used from the development perspective as in this, we specify the functionality at one place and then use it in the whole application.

This has an advantage as it reduces the amount of code and makes the code easy to maintain.

Understanding MVC Validation with an Example

In this example, we will use annotations. The order that we follow in this example is: First, we will create the controller, then the model, and after that, the view followed by output.

Controller

This is the syntax for creating a controller. Here we are creating a student controller:

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Web;  
using System.Web.Mvc;  
namespace MvcApplicationDemo.Controllers  
{  
    public class StudentsController : Controller  
    {  
        // GET: Students  
        public ActionResult Index()  
        {  
            return View();  
        }  
    }  
} 

Model

Here we are creating a student model:

using System.ComponentModel.DataAnnotations;  
  
namespace MvcApplicationDemo.Models  
{  
    public class Student  
    {  
        public int ID { get; set; }  
        // -- Validating Student Name  
        [Required(ErrorMessage ="Name is required")]  
        [MaxLength(12)]  
        public string Name { get; set; }  
        // -- Validating Contact Number  
        [Required(ErrorMessage = "Contact is required")]  
        [DataType(DataType.PhoneNumber)]  
        [RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Not a valid Phone number")]  
        public string Contact { get; set; }
        // -- Validating Email Address  
        [Required(ErrorMessage ="Email is required")]  
        [EmailAddress(ErrorMessage = "Invalid Email Address")]  
        public string Email { get; set; }  
       
    }  
}

View

Now this will be the view that is visible to the user on the front end:

@model MvcApplicationDemo.Models.Student  
@{  
    ViewBag.Title = "Index";  
}  
<h2>Index</h2>  
@using (Html.BeginForm())  
{  
    @Html.AntiForgeryToken()  
    <div class="form-horizontal">  
        <h4>Student</h4>  
        <hr />  
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })  
        <div class="form-group">  
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })  
            </div>  
        </div>  
   <div class="form-group">  
            @Html.LabelFor(model => model.Contact, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.Contact, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.Contact, "", new { @class = "text-danger" })  
            </div>  
        </div> 
        <div class="form-group">  
            @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.Email, "", 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-default" />  
            </div>  
        </div>  
    </div>  
}  
<div>  
    @Html.ActionLink("Back to List", "Index")  
</div>  
@section Scripts {  
    @Scripts.Render("~/bundles/jqueryval")  
} 

Output

We can see in the below attached screenshot that it validates the empty fields and displays the message that these fields are required.

In the below-attached screenshot, we are validating the entered data.

 

Frequently Asked Questions

1. Write some features of ASP.NET.

Answer: It can separate server-side code with the HTML layout and uses C# and VB.NET as languages to make the website.

2. What is a round trip?

Answer: It is the trip of a web page from client to server and then again from server to client.

3. Name some page events in ASP.NET.

Answer: Some page events in ASP.NET are preinit, init, PreLoad, Load, Render, PreRender, etc.

4. How many types of validations are there in ASP.NET?

Answer: There are mainly two validations in ASP.NET: client-side and server-side.

Key Takeaways

In this blog, we have learned about MVC validations by explaining the base class validator, the standard annotations used during validation, and examples with Model, View, Controller.

 If you want to learn about Webform LinkButton in ASP.Net, look at this blog. Here, you will get the idea of what they are and the Features Of ASP Net with examples.

Recommended Readings:

 

Live masterclass