Custom MVC validation attribute

Finding my self in a new-old situation i needed to create a custom validation attribute.

To create an custom validation attribute we inherit from the abstract class “ValidationAttribute” in System.ComponentModel.DataAnnotations. This allows for server side validation by invoking the method “IsValid”.

I decided to implement an “MoreThan” attribute which checks that the one value in my model is more than another. For this we need the validator to compare the model property with another property.

This is how the validator class looks like.

To use it we simply add the “MoreThan” attribute to our model property with a comparison property of a string.

If we want to use the jQuery obtrusive validation we need to add an “IClientModelValidator” interface to our custom validation class. This makes the internal tag helper to know about the validation.

So how can we test if the custom validator work? Lets implement a simple xunit test where we test the validitiy and the error message we want it to show.

Now, go create your custom validators to satisfy your needs.

Leave a Comment

Your email address will not be published. Required fields are marked *