Reputation: 2682
I use FluentValidation 3
and I have a strange problem when I use overloaded WithMessage methods.
A composite format string are not formatting correct. I get "true
" instead of {0}
in my format string. All other format items are not replaced.
For example:
public class MyModelValidator : AbstractValidator<MyModel>
{
public MyModelValidator()
{
RuleFor(x => x.Caption).NotNull().WithMessage("{0} ----- {1}", "one", "two" );
}
}
Validation string which I get is: "true----- {1}
" instead of "one----- two
".
Could you explain me, what is wrong in my code?
Upvotes: 1
Views: 1727
Reputation: 60503
Well, response is... in the source Code.
You use this overload (not really clear in its usage, I must say) of WithMessage
:
public static IRuleBuilderOptions<T, TProperty> WithMessage<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, string errorMessage, params object[] formatArgs) {
var funcs = ConvertArrayOfObjectsToArrayOfDelegates<T>(formatArgs);
return rule.WithMessage(errorMessage, funcs);
}
So "one" and "two" are changed to an array of Func<T, object>
, wich, of course, will lead to strange behaviours with your code...
You should use string.Format
in your case
WithMessage(string.Format("{0} ----- {1}", "one", "two" ));
By the way, FluentValidation messages are "already preformatted" :
The goal to use {0}
in WithMessage is to modifiy the text around {0}
.
For example, NotNull has a "1 argument" preformatted message.
That's why your {0}
is transformed to "true", I think.
Upvotes: 1