FluentValidation is really powerful, but this power also makes it sometimes complex to find the correct way to solve a specific problem. In this case I wanted to conditionally execute a certain validation when data in another field was filled in.
FluentValidation makes this possible through the usage of the When/Unless methods. Here is a short example:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
RuleFor(x => x.FastDelivery) | |
.NotEmpty() | |
.WithState(x => new ValidationState() { | |
Code = "FastDelivery.empty", | |
Keys = { ValidationKeys.Delivery } | |
}); | |
RuleFor(x => x.DeliveryDate) | |
.NotEmpty() | |
.WithState(x => new ValidationState() | |
{ | |
Code = "DeliveryDate.empty", | |
Keys = { ValidationKeys.Delivery } | |
}) | |
.When(x=> x.FastDelivery == true); |
We only validate the DeliveryDate when FastDelivery is choosen.