Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad practice to use FluentValidation for doing deeper database validation?

For example, you may validate a phone number or email, those are all over FV documentation, but what if you need to make sure the phone number is not already in use by an employee of manager "X"? I know its possible to do this through all the custom validator options. But should I be doing it there?

If I put this logic into a complex custom FluentValidation thingy I worry that I am coding in this logic in the wrong place. Traditionally, I would just add this to my service in the areas where I would normally be doing a add/save.

Since I already have fluent validation set up for my view model, and I am doing other types of validations there, it seems enticing to keep everything in one place. However, this means if I ever reuse my logic in a non web app ill have to remember to execute these validators some other way instead of this being automated via the modelbinder IsValid(). Although I did not spend the extra time coding to make my project this modular anyway. I digress.

like image 922
Victorio Berra Avatar asked Jan 28 '23 17:01

Victorio Berra


1 Answers

Well no it is actually a good place. You will want to keep the validation at the same place and make it reusable for your logic, no matter the underlying framework.

Using attribute-validation and ModelStateDictionary in ASP.NET bounds your logic to ASP.NET while FluentValidation can be used with everything. You could still use a service to wrap that logic and only add / update entities there when validation succeeds. I heavily use fluentvalidation, even for scenarios where I need to do database-queries and it works just fine. I could simply switch from ASP.NET to a console application or whatever, and have the very same logic for both.

Having validation logic splitted into several areas sounds not like best practice.

like image 144
alsami Avatar answered May 01 '23 04:05

alsami