ASP.NET Core – Client-side custom validation attributes

I wrote about how to add custom validation attributes. These are used for model validation on the server-side. You can also use these for client-side validation, which I’ll show in this article. 1 – Implement IClientModelValidator The first step is to implement the IClientModelValidator interface in the custom validation attribute class. This has a single … Read more

ASP.NET Core – How to manually validate a model in a controller

Manually validating a model can mean a few different things. It depends on what you’re trying to do exactly. Are you trying to validate a model object against its validation attributes? Use TryValidateModel(). Are you trying to do validation logic manually (instead of using validation attributes)? You can add errors to ModelState in that case. … Read more

C# – Manually validate objects that have model validation attributes

You can use the Validator utility class to do manual attribute-based validation on any object, in any project type (as opposed to doing automatic model validation in ASP.NET). To do this, add model validation attributes to your class properties, then create an object and populate it (aka binding), and finally execute manual validation with the … Read more

C# – How to unit test a model validation attribute

You can unit test a validation attribute by creating an instance of it and then testing the two methods: In this article, I’ll show examples of unit testing these methods in a custom validation attribute and in a built-in validation attribute (i.e. [Range]). Unit testing a custom validation attribute Consider the following custom validation attribute … 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