How to pass value to error message using free check

Is it possible to pass the value to the error message. I tried something like this:

RuleFor(x => x.ForeName).Length(1, 255).WithLocalizedMessage(() => String.Format(ValidationErrors.TooLong, "255")); 

ValidationErrors is a resource file that contains:

TooLong Please use less than {0} characters.

It:

 RuleFor(x => x.ForeName).Length(1, 255).WithLocalizedMessage(() => ValidationErrors.TooLong); 

works great.

+4
source share
1 answer

In the current version of FluentValidation (v2), this is not supported when using localized messages.

The first argument to WithLocalizedMessage should always identify the property of the resource - you cannot place arbitrary code there (for example, calling string.format).

If you are using a non-localized message, you can do this:

 RuleFor(x => x.Property).Length(1,255).WithMessage("Max number of chars is {0}", "255"); 

You can also use this approach with localized error messages with FluentValidation v3, but there is no binary version, so if you want to use this, you can capture and build the source from the project site.

Alternatively, instead of using numeric placeholders, you can use the native FV support for name placeholders for default validators. Therefore, if you use .Length (1, 255), you can use {MaxLength} inside your error message instead of {0}:

Please use less characters {MaxLength}.

... and FV will automatically replace this with the value you entered as maximum. There is a complete list of all named placeholders in the documentation .

+6
source

All Articles