brainit
Published in

brainit

ASP.NET Core Fluent Validation

Validation is a process to validate and check the data inserted by the user. Every MVC application needs some kind of validation, either for the DTO model or Entity. So why not use Fluent Validation?

Fluent Validation is a .NET library that uses lambda expressions for building validation rulers. Using Fluent Validation you can create some advance and complex validation for the user data. Let’s get it started.

First, from the command line or NuGet package manager install FluentValidation.AspNetCore.

For ASP.NET to discover your validators, they must be registered with the services collection. The best way to do that is by using the RegisterValidationsFromAssemblyContaining method to automatically register all validators within a particular assembly. This will automatically find any public, non-abstract types that inherit from AbstractValidator and register them with the container

Validate incoming request

This next example assumes that the UserValidator is defined to validate a class called User.

When you send a post request, MVC’s model-binding infrastructure will validate the User object with UserValidator. If a request is not valid, you get response messages with corresponding errors which are shown below.

Custom Validators

With plenty of built-in validators, Fluent Validator offers custom validators. The recommended way is to make use of the Predicate Validator to write a custom validation function. The simplest way to implement a validator is by using Must method, which internally uses the PredicateValidator.

To make this logic reusable, we can wrap it in an extension method that acts upon any List<string> type.

Our rule definition can now be rewritten to use our custom method.

Conclusion

Fluent Validation is a powerful tool to validate DTOs, entities, etc. Using this validator you can write simpler and more cleaner code. For more cool stuff feel free to visit the official Fluent Validation documentation.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store