My go-to library for model validation in .NET is Fluent Validation, and I have written a number of posts about it before. On the current project I am working we needed to do database validation which I described how to do in this blog post. This time however I needed to go one step further and not only do the database validation on the server side, but also on the client side.
In the previous blog post we added dependency injection to our project and created our own validation factory which resolves the validators using dependency injection. In this, the final blog post of the series, we will have a look at extending our existing RegisterModelValidator to do some database validation. The database is accessed using the repository pattern which allows us to mock the repository and enable us to unit test the validator without a physical database.
In the previous blog post we looked at how to do unit testing with FluentValidation. My goal is to show you how we can write validators which can validate information in the database, but still be easy to unit test. For this we will make use of dependency injection, mocking and the repository pattern. Before we can write and unit test the actual database validator we need to put dependency injection in place as it will make things a bit easier for us going ahead.
In my previous blog post I looked at the basics of setting up and using FluentValidation with ASP.NET MVC. This time around we will be having a look at unit testing with FluentValidation. There are a few approaches to do validation of your model or view model objects using data annotations. One of the ways to do this is by using the approach described by K. Scott Allen in this blog post.
One of the most popular ways to do model validation in the ASP.NET MVC Framework is surely to use the built-in model validation features using data annotations. This will probably work fine in most instances, but I prefer using the Fluent Validation library in my own projects mainly because of how easy it is to unit test validation rules, as well as the fact that I can split the validation rules completely from the underlying model.