How to Add Form Validation to an ASP.NET Core MVC App

In this blog post, we are going to show you how to add form validation to an ASP.NET Core MVC app.

We will be using the popular ASP.NET Core Validation Library for this purpose. This library makes it easy to validate your input data and helps you avoid common security issues.

Form validation is the process of ensuring that the user has inputted valid data into a form. This is important to do to avoid common security issues, such as SQL injection attacks. The ASP.NET Core Validation Library makes it easy to validate your input data. In this blog post, we will show you how to use this library in your ASP.NET Core MVC app.

DataAnnotations Library

DataAnnotations is a set of attributes that you can use to decorate your data classes. These attributes help you to define the validations that you want to apply to your data.

The DataAnnotations library is included in the .NET Core framework. This means that you can use it in any ASP.NET Core application

Add Validation

To add form validation to my ASP.NET application, I will add the following library to my MVC model class.

using System.ComponentModel.DataAnnotations;

In the form configuration, I will add the following code. In my case, I have two fields (Name and email).

The first two lines add validation to the name filed, and the last two files add validation to the EmailAddress filed.

 [Required(ErrorMessage = "Please enter your name")]
 [ StringLength(4,MinimumLength = 2)]
 [Required(ErrorMessage = "Please enter your email address")]

[EmailAddress]

Code

The end to end code is shown below.

using System.ComponentModel.DataAnnotations;
namespace simpleForm.Models
{
    public class formClass
    {
        [Required(ErrorMessage = "Please enter your name")]
        [ StringLength(4,MinimumLength = 2)]
        public string? Name { get; set; }

        [Required(ErrorMessage = "Please enter your email address")]
        [EmailAddress]
        public string? Email { get; set; }
    }
}

Leave a comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.