How to do Model Validation in Asp.net Core?

Model Validation in .NET core:

Model validation is an essential part of any web application that deals with user input. In ASP.NET Core, model validation can be performed by using built-in validation attributes and model binding. Here are the steps to perform model validation in ASP.NET Core:

1.Define validation attributes on model properties:

 ASP.NET Core provides  System.ComponentModel.DataAnnotations namespace in which we get several built-in validation attributes that can be used to specify the validation rules for model properties.For example, the [Required] attribute can be used to specify that a property is required, while the [EmailAddress] attribute can be used to validate that a property contains a valid email address.



2.Enable model validation: 

To enable model validation in ASP.NET Core, you need to add the [ApiController] attribute to your controller class and call the [FromBody] attribute on the input parameter of the action method. This will automatically bind the request body to the input parameter and validate the model.




3.Check model state:

 The ModelState property of the controller class contains the validation errors for the model. You can check the IsValid property to determine whether the model is valid or not. If the model is not valid, you can return a bad request response with the ModelState.


With these steps, you can perform model validation in ASP.NET Core and ensure that the user input is valid before processing it further.

Comments

Popular posts from this blog

MS SQL Differences for Dot net Interview

.Net core 3.1 Folder structure