ASP.NET Validations: Everything you need to know

24 December 2021 at 10:00 by ParTech Media - Post a comment

In today’s world, human-to-human interaction has reduced drastically while human-to-computer interaction has multiplied. This is applicable in most of the fields including banking, education, eCommerce, and so on. In most of these fields, there is a need to fill out some details by the user.

For example, while booking air tickets, it is necessary to provide the first name, last name, mobile, and email address. Also, in some cases, users are asked to create an account on travel websites. When we take inputs from the user, the most common thing that needs to be done from the application's end is the validation of the input. It is a crucial step, as it could prevent errors in the backend and avoid unnecessary confusion later on.

Imagine you are on a travel website and booking a ticket. Now if there are no validations which state that the email id field is mandatory and you forget to enter the email, where will you receive the ticket. What if the browser gets closed automatically and you have no way to access the ticket.

Such kinds of errors can be avoided by having a simple validation in the front end. Also if you are an organization with multiple front-end applications, then it becomes tedious to write logic individually for validating all the inputs in all the applications. To address this, ASP. Net provides built-in validations to check the users’ inputs based on the requirements. Let us understand more about it in this blog.

Table of contents

  1. Introduction to ASP.NET Validation
  2. Implementing validations in an ASP.NET project
  3. Conclusion

Introduction to ASP.NET Validation

One of the Unique Selling Points of ASP.Net is its in-built validation which is available while building websites. It provides a set of validations that are easy to use and diligently checks for errors and highlights them to the user. Here are some validations that come along with ASP.Net -

  1. RequiredFieldValidation
  2. CompareValidato
  3. RangeValidator
  4. RegularExpressionValidator
  5. CustomValidator

Let’s now understand how to implement them in an application.

Implementing validations in an ASP.NET project

To understand the validation in ASP.Net, we are going to create an ASP.Net Core Web App and then create a form that takes a few personal details as input from the user. We will apply validations on top of it.

First, create a project with ASP.NET Core Web App as the template and provide a valid name to the solution.

Once created, the solution looks like below. It is in the MVC (Model-View-Controller) structure.

The next step is to create a model which can hold the data for the user inputs. Create a model with name, gender, date of birth, phone number, email, password, and confirm password.

The model has to be added under the Models folder and named as PersonalDetails. Below is the code for the same.

using System;
using System.ComponentModel.DataAnnotations;

namespace PARTECH_ValidationControls.Models
{
  public class PersonalDetails
  {
​    [Key]
​    public int Id { get; set; }

​    [Required(ErrorMessage = "Please enter a name")]
​    [StringLength(100, ErrorMessage = "Name cannot be more than 100 characters.")]
​    public string Name { get; set; }

​    [Required(ErrorMessage = "Please provide a gender")]
​    public string Gender { get; set; }

​    [Required(ErrorMessage = "Please enter date of birth")]
​    [Display(Name = "Date of Birth")]
​    [DataType(DataType.Date)]
​    public DateTime DateofBirth { get; set; }

​    [Required(ErrorMessage = "Please enter phone number")]
​    [Display(Name = "Phone Number")]
​    [Phone]
​    public string PhoneNumber { get; set; }

​    [Required(ErrorMessage = "Please enter email address")]
​    [Display(Name = "Email Address")]
​    [EmailAddress(ErrorMessage = "Please enter a valid email address")]
​    public string Email { get; set; }

​    [Required(ErrorMessage = "Please enter password")]
​    [DataType(DataType.Password)]
​    public string Password { get; set; }

​    [Required(ErrorMessage = "Please enter confirm password")]
​    [Display(Name = "Confirm Password")]
​    [Compare("Password", ErrorMessage = "Password and confirm password does not match")]
​    [DataType(DataType.Password)]
​    public string ConfirmPassword { get; set; }
  }
}

Here, in the Model properties, we are going to specify the validations that are required for each property. Say, Password and Confirm Password properties should have the same value (Compare validator will be used), Name is mandatory (Required Validator will be used). For email address, email address validation attribute will be used, and so on.

As the Model is created, the next step is to consume the Model by providing a front end for it. Create a View for the model by scaffolding. Right-click on the Home folder present inside the Views folder, then click on ‘Add’ and then ‘View’. A dialog box opens asking for options. Choose the ‘Razor View’ option and in the next screen choose, Template as ‘Create’ and Model class as ‘PersonalDetails’ and then click on ‘Add’.

On clicking ‘Add’, a new cshtml file under the Home folder gets created.

Name it as PersonalDetails.cshtml.

By default, the MVC application executes the Index action method in the Home controller. To call the PersonalDetails page by default, we are going to modify the endpoint route in the StartUp.cs file. Under the Configure method in the Startup.cs file, modify the app.UseEndpoints as below. This will (by default) route the application to the PersonalDetails action method in the HomeController.

 app.UseEndpoints(endpoints =>

​      {
​        endpoints.MapControllerRoute(
​          name: "default",
​          pattern: "{controller=Home}/{action=PersonalDetails}/{id?}");
​      });

The Next step is to create a PersonalDetails action method in the Home Controller which returns a view. Add the below lines in the HomeController.cs file.

public IActionResult PersonalDetails()

​    {
​      return View();
​    }

Now, if we run the solution, the application lands on the below form page.

If we click on the Create button at the end of the page, the error message comes up on the screen for the fields which are required.

If we enter an invalid email address, then the error message - ‘Please enter a valid email address’ appears.

Similarly, if we enter mismatching passwords in Password and Confirm Password fields, the error message - ‘Password and confirm password does not match’ appears.

Conclusion

ASP.Net provides validators that can handle most of the basic input field validations thus reducing the developers’ effort in developing the same. It also provides consistency of validation across the application.

Latest