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.
You’ll need to pull in a copy of FluentValidation and FluentValidation.AspNetCore from Nuget.
First of all we need a basic view model with some fields to validate.
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.
Next we need to inject the validator class into our platform at startup.
Let’s put together a simple form with a post back for our data model.
Now let’s submit a blank version of our page data to the controller.
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.
Finally, let’s submit a fully valid post back
…and see how our fluent validation responds?
…Success! As mentioned before, FluentValidation provides a much cleaner method of carrying out strongly typed data model validation than the traditional DataAnnotations namespace.