开发者

How to pass a value into the error message using fluent validation

开发者 https://www.devze.com 2023-03-15 08:13 出处:网络
Is it possible to pass a value into the error message. I have tried something like this: RuleFor(x =>开发者_高级运维; x.ForeName).Length(1, 255).WithLocalizedMessage(() => String.Format(Validati

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

RuleFor(x =>开发者_高级运维; x.ForeName).Length(1, 255).WithLocalizedMessage(() => String.Format(ValidationErrors.TooLong, "255"));

ValidationErrors is my resource file which contains:

TooLong Please use fewer than {0} characters.

This:

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

works fine.


With the currently released version of FluentValidation (v2), this isn't supported when using localized messages.

The first argument to WithLocalizedMessage must always identify a resource property - you can't place arbitrary code inside there (such as a call to string.format).

If you're using a non-localized message then you can do this:

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

You'll also be able to use this approach with localized error messages as of FluentValidation v3, but there's no binary release yet so if you want to make use of this then you could grab and build the source from the project site.

As an alternative, instead of using numerical placeholders you can use FV's built in support for named placeholders for the default validators. So if you're using .Length(1, 255) then you can use {MaxLength} inside your error message instead of {0}:

Please use fewer than {MaxLength} characters.

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号