Reputation: 13972
In the context of a data-oriented application, that uses a database:
I was using FluentValidations
only to validate things like that an Id was a positive number, or that an argument isn't null
: Things that didn't hit the database.
But after some time, I wondered why wouldn't I validate things that actually query the database. So I decided to validate further and now, my Validator
not only validates that the specified Id is a positive number, but also that the entity exists.
Is this the goal of a Validator. Am I misusing it? Should a Validator check also complex business rules?
Upvotes: 1
Views: 1300
Reputation: 5082
IMHO, it's totally fine to use FluentValidator
for checking business rules. But it's better to separate business rules from simple validation. For example if it's ASP.NET application general validation should be performed in the Presentation layer(like using ModelState
) but business rules should come into play in the Domain layer(e.g. in some service or decorator).
You can find these links useful:
Upvotes: 2
Reputation: 376
There are 2 ways to do this kind of validations:
1.Create a class and inherit from ProperyValidator and use it to the entity validations class.
public class UniqueValidator<T> : PropertyValidator where T:class
{
//inject the repository
protected override bool isValid(PropertyValidatorContext context){
//check the validity
}
}
2.Create method directy to the EntityValidation class
public class EntityValidation : AbstractValdiation<Entity>{
//inject the repository
//your current validations
public bool UniqueValue(Entity instance){
//query to validate
}
}
Upvotes: 0