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
Extension methods based on ErikE's answer.
public static class RuleBuilderOptionsExtensions
{
public static IRuleBuilderOptions WithMessage(this IRuleBuilderOptions rule, Func func)
=> DefaultValidatorOptions.WithMessage(rule, "{0}", func);
public static IRuleBuilderOptions WithMessage(this IRuleBuilderOptions rule, Func func)
=> DefaultValidatorOptions.WithMessage(rule, "{0}", func);
}
Usage examples:
RuleFor(_ => _.Name).NotEmpty()
.WithMessage(_ => $"The name {_.Name} is not valid for Id {_.Id}.");
RuleFor(_ => _.Value).GreaterThan(0)
.WithMessage((_, p) => $"The value {p} is not valid for Id {_.Id}.");