March 23, 2019

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

Looking to validate an HTML view at post back? Chief Technology Officer (CTO) Simon Gilbert explains the steps required to bind your validation rules to an HTML view, using the FluentValidation library and 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

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 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

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

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

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

Finally, let’s submit a fully valid post back

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

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

Download Github Code Sample

Feel free to DOWNLOAD the sample code of the aforementioned implementation from my Github account.