I am using FluentValidation and I want to format a message with some of the object\'s properties value. The problem is I have very little experience with expressions and delegat
While KhalidAbuhakmeh's answer is very good and deep, I just want to share a simple solution to this problem. If you afraid of positional arguments, why not to encapsulate error creation mechanism with concatenation operator +
and to take advantage of WithMessage
overload, that takes Func
. This CustomerValudator
public class CustomerValidator : AbstractValidator
{
public CustomerValidator()
{
RuleFor(customer => customer.Name).NotEmpty().WithMessage("{0}", CreateErrorMessage);
}
private string CreateErrorMessage(Customer c)
{
return "The name " + c.Name + " is not valid for Id " + c.Id;
}
}
Prints correct original error message in next code snippet:
var customer = new Customer() {Id = 1, Name = ""};
var result = new CustomerValidator().Validate(customer);
Console.WriteLine(result.Errors.First().ErrorMessage);
Alternatively, use an inline lambda:
public class CustomerValidator : AbstractValidator
{
public CustomerValidator()
{
RuleFor(customer => customer.Name)
.NotEmpty()
.WithMessage("{0}", c => "The name " + c.Name + " is not valid for Id " + c.Id);
}
}