In addition, you can read more about Data Annotations for model validation in ASP.NET Core.
Data Annotations can be used in ASP.NET Core MVC and Web API as a model validator.
They get assigned as attributes to properties which then get used when model validation is performed.
In-addition to the Data Annotations available in System.ComponentModel.DataAnnotations
, a custom Data Annotation validator can be created.
This code sample provides a custom Data Annotation validator that will validate the age of a customer based on their date of birth.
If the customer is 18 years or older, the validator successfully passes. However, if they are under 18, the validation fails with a custom error message returned.
It is used in the CustomerModel
model which gets passed in as an endpoint in the CustomerController
.
This is the software that will need to be installed onto your machine.
These are the steps to get the application working.
You are now ready to go.
Open up RoundTheCode.DA.sln
in Visual Studio 2022.
Start the project in Visual Studio.
A browser should load up the application automatically. If it doesn't, hit https://localhost:7001/swagger
, and test out the customer API endpoint.
Watch our video where we go ahead and talk through this custom Data Annotation validator and test it out in an ASP.NET Core Web API.
In addition, you can read more about Data Annotations for model validation in ASP.NET Core.