Binding Fluent Validation to an HTML View - C# ASP.Net MVC Core

Binding Fluent Validation to an HTML View - C# ASP.Net MVC Core

Strongly-Typed Data Model Validation

Previously I discussed using the FluentValidation library to implement strongly-typed data model validation in C# .Net Core. Today we’re going to look at injecting that validation to an HTML view in C# ASP.Net MVC Core, making use of the standard ModelState syntax in MVC.

Nuget Packages

You’ll need to pull in a copy of FluentValidation and FluentValidation.AspNetCore from Nuget.

Let’s Code…

First of all we need a basic view model with some fields to validate.

C# ASP.Net MVC Core - Fluent Validation Data Model

C# ASP.Net MVC Core - Fluent Validation Data Model

Abstract Validator Inheritance

Now that we have a data model, we can create a validation class which inherits from AbstractValidator. In this case I’ve separated the FirstName field from the technical data about our new user for cleanliness.

C# ASP.Net MVC Core - Fluent Validation Abstract Validator

C# ASP.Net MVC Core - Fluent Validation Abstract Validator

C# ASP.Net MVC Core - Fluent Validation View Model Validator

C# ASP.Net MVC Core - Fluent Validation View Model Validator

Startup Configuration

Next we need to inject the validator class into our platform at startup.

C# ASP.Net MVC Core - Fluent Validation Configure Services

C# ASP.Net MVC Core - Fluent Validation Configure Services

HTML View

Let’s put together a simple form with a post back for our data model.

C# ASP.Net MVC Core - Fluent Validation HTML View

C# ASP.Net MVC Core - Fluent Validation HTML View

C# ASP.Net MVC Core - Fluent Validation HTML

C# ASP.Net MVC Core - Fluent Validation HTML

Now let’s submit a blank version of our page data to the controller.

C# ASP.Net MVC Core - Fluent Validation HTML Errors

C# ASP.Net MVC Core - Fluent Validation HTML Errors

As you can see, our fluent validation has kicked in with very little else required in terms of implementation. Let’s amend the data slightly and see how our validation errors change.

C# ASP.Net MVC Core - Fluent Validation HTML Different Errors

C# ASP.Net MVC Core - Fluent Validation HTML Different Errors

Finally, let’s submit a fully valid post back

C# ASP.Net MVC Core - Fluent Validation HTML Valid

C# ASP.Net MVC Core - Fluent Validation HTML Valid

…and see how our fluent validation responds?

C# ASP.Net MVC Core - Fluent Validation HTML Successful Validation

C# ASP.Net MVC Core - Fluent Validation HTML Successful Validation

Success! As mentioned before, FluentValidation provides a much cleaner method of carrying out strongly typed data model validation than the traditional DataAnnotations namespace.

Enjoy!