Using FluentValidation's WithMessage method with a list of named parameters

Jason picture Jason · Jan 5, 2013 · Viewed 18.2k times · Source

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 delegates in C#.

FluentValidation already provides a way to do this with format arguments.

RuleFor(x => x.Name).NotEmpty()
    .WithMessage("The name {1} is not valid for Id {0}", x => x.Id, x => x.Name);

I would like to do something like this to avoid having to change the message string if I change the order of the parameters.

RuleFor(x => x.Name).NotEmpty()
    .WithMessage("The name {Name} is not valid for Id {Id}", 
    x => new
        {
            Id = x.Id,
            Name = x.Name
        });

The original method signature looks like this:

public static IRuleBuilderOptions<T, TProperty> WithMessage<T, TProperty>(
    this IRuleBuilderOptions<T, TProperty> rule, string errorMessage, 
    params Func<T, object>[] funcs)

I was thinking of providing this method with a list of Func.

Anyone can help me with this?

Answer

ErikE picture ErikE · Mar 21, 2016

If you are using C# 6.0 or later, here's an improved syntax.

With version 8.0.100 or later of Fluent Validation, there is a WithMessage overload that takes a lambda accepting the object, and you can just do:

RuleFor(x => x.Name)
   .NotEmpty()
   .WithMessage(x => $"The name {x.Name} is not valid for Id {x.Id}.");

However, with earlier versions of Fluent Validation this somewhat hacky way is still pretty clean, and a lot better than forking its older versions:

RuleFor(x => x.Name)
   .NotEmpty()
   .WithMessage("{0}", x => $"The name {x.Name} is not valid for Id {x.Id}.");