Data Annotation custom validator 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.

  • Visual Studio 2022 version 17.4.4 or above. It will work with the free community version.
  • .NET 7 SDK version 7.0.2 or above. Visual Studio 2022 should already have the .NET SDK installed.

Get the application working

These are the steps to get the application working.

  • Fill out the code example form. We will send you an email where you can download the code example.

You are now ready to go.

Open the project in Visual Studio

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.

More information

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.