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.
public class Person { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public DateTime BirthDay { get; set; } }
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.
public class PersonValidator : AbstractValidator<Person> { public PersonValidator() { RuleFor(e => e.FirstName).NotEmpty().MaximumLength(30); RuleFor(e => e.LastName).NotEmpty().MaximumLength(30); } }
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.
public static class CustomValidators { public static IRuleBuilderOptions<T, string> NotStartWithWhiteSpace<T>(this IRuleBuilder<T, string> ruleBuilder) { return ruleBuilder.Must(m => m != null && !m.StartsWith(" ")).WithMessage("'{PropertyName}' should not start with whitespace"); } public static IRuleBuilderOptions<T, string> NotEndWithWhiteSpace<T>(this IRuleBuilder<T, string> ruleBuilder) { return ruleBuilder.Must(m => m != null && !m.EndsWith(" ")).WithMessage("'{PropertyName}' should not end with whitespace"); } }
You can use the custom validators in the PersonValidator in the following way:
public class PersonValidator : AbstractValidator<Person> { public PersonValidator() { RuleFor(e => e.FirstName).NotEmpty().MaximumLength(30).NotStartWithWhiteSpace().NotEndWithWhiteSpace(); RuleFor(e => e.LastName).NotEmpty().MaximumLength(30).NotStartWithWhiteSpace().NotEndWithWhiteSpace(); } }
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.
Can Fluent Validation be written using
Visual Basic.NET ? If so, where can I see how to write the RuleFor( ) statement using VB.NET ?
I don’t know… I’m not the owner of fluent validation. And I’m a C# guy!