ASP.NET Core – How to unit test a model validation attribute

You can directly unit test a model validation attribute by creating an instance of the attribute class, and then testing the two primary methods: IsValid() and FormatErrorMessage(). Here’s an example of unit testing a custom validation attribute: You can also test the built-in validation attributes (such as [Range], [RegularExpression], etc..), which is useful when you … Read more

ASP.NET Core – Create a custom model validation attribute

There are many built-in model validation attributes available – such as [Required] and [Range] – which you can use to handle most validation scenarios. When these aren’t sufficient, you can create a custom validation attribute with your own validation logic. I’ll show an example of how to do that. 1 – Subclass ValidationAttribute and implement … Read more