How to automate model validation in ASP.Net Core

Take advantage of automatic model state validation in ASP.Net Core to avoid tedious manual coding for HTML form validation

Become An Insider

Sign up now and get FREE access to hundreds of Insider articles, guides, reviews, interviews, blogs, and other premium content. Learn more.

When we create applications that accept data from users, we must validate that data before storing it in a database. The .Net Framework not only provides validation attributes to simplify checks for required input, data types, value ranges, and patterns (e.g. email addresses and credit card numbers), but ASP.Net Core can check for validation errors in submitted HTML form values automatically. 

A model state in ASP.Net Core is a collection of name-value pairs, along with validation information, that is sent to the server during a POST request. Any error messages included in the validation information are the model validation errors. The ApiController attribute introduced in ASP.Net Core 2.1 handles model state validation automatically. If the model state is invalid, it returns the appropriate error. 

This article presents a discussion of how we can work with this new feature in ASP.Net Core.

Create an ASP.Net Core application in Visual Studio

In this section we will create the ASP.Net Core application we will use to learn how we can work with the ApiController attribute. Follow the steps outlined below to create a new ASP.Net Core project in Visual Studio 2017.

To continue reading this article register now