'Add error message without using WithMessage() method in FluentValidation
I have a question and would be grateful if anyone can help me. I am validating an object with "FluentValidation" in an ASP.NET project, and I would like to know if there is a way to add an error message in "ValidationResult" without using the WithMessage () method. I am needing to add an error message based on a condition that is not related to the properties of the validated class. I thank the attention.
Solution 1:[1]
When you write a custom validator for instance.
see FluentValidation documentation. You can see here a screen from Visual Studio
where an ErrorMessage-string is added. Here's some actual code for such a rule
RuleFor(customerCreateCommand => customerCreateCommand.Dto.Addresses)
.Custom((addresses, context) =>
{
bool includesBillingAddress = false;
foreach (AddressDto address in addresses)
{
if (address.AdressTypeId == Commons.Enums.AddressType.Billing)
{
includesBillingAddress = true;
}
}
if (includesBillingAddress == false) { context.AddFailure("A customer profile needs a billing address"); }
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | qqtf |
