Creating custom validators with FluentValidation

This blog post will explain how creating custom validators with FluentValidation. A while back I wrote a blog post about how to start with FluentValidation in your project. In this post we will continue on that foundation.

Let’s say in example you have the class Person.

You need to validate that Person class. So let’s say, you want to validate the FirstName and LastName property. Those properties are similar to each other because both are name and a string so both could have the same (custom) validators. 

So let’s create a PersonValidator class which of course will validate the Person class.

Custom Validator

Now, you want to extend the basic validators. So let’s say you want a validator that the name must not start with a whitespace. You can validate this on multiple ways but the most logical way is to create a custom validator once and use that validator on multiple places.

Here is the validator for checking whitespaces in the begin or end of a string.

You can use the custom validators in the PersonValidator in the following way:

With this above custom validator is validating your objects very easy to do.

In the next blog post we go one step further. I will then show you how to apply the same validation rules on multiple classes.