FluentValidation 和自定义消息告诉用户哪些值是 allowed/expected

FluentValidation and custom message that tells the user which values are allowed/expected

考虑以下验证器,它按预期工作:

public class NewOrderSingleValidator : AbstractValidator<NewOrderSingle>
{
    public NewOrderSingleValidator()
    {
        RuleFor(o => o.OrdType.getValue())
            .Must(p => p == OrdType.LIMIT || p == OrdType.MARKET)
            .WithMessage("Provided OrdType is not allowed, the value was: {PropertyValue}")
            .When(o => o.IsSetOrdType());
    }
}

只要验证失败,验证结果就会包含错误 Provided OrdType is not allowed, the value was: FOO。好,太棒了!

但现在我想知道如何才能告诉用户哪些值是允许的,而无需在消息中重复我的规则。

我不太明白 documentation 的意思:

‘{PropertyValue}’ - The value of the property being validated These include the predicate validator (‘Must’ validator), the email and the regex validators.

我希望能够做这样的事情:

public class NewOrderSingleValidator : AbstractValidator<NewOrderSingle>
{
    public NewOrderSingleValidator()
    {
        RuleFor(o => o.OrdType.getValue())
            .Must(p => p == OrdType.LIMIT || p == OrdType.MARKET)
            .WithMessage("Error! Provided value: {PropertyValue}! Expected values: {Must}")
            .When(o => o.IsSetOrdType());
    }
}

这应该生成以下消息(或类似消息):Error! Provided value: FOO! Expected LIMIT or MARKET

我认为在这种情况下,您可以尝试将代码重构为如下内容:

var allowed = new [] {OrdType.LIMIT, OrdType.MARKET};
RuleFor(o => o.OrdType.getValue())
        .Must(p => allowed.Contains(p))
        .WithMessage($"Error! Provided value: {{PropertyValue}}! Expected values: {string.Join(", ", allowed)}")
        .When(o => o.IsSetOrdType());

I don't really understand what the documentation means by:

表示 PropertyValue 占位符将被提供给相应 validator 的值替换。一些内置的占位符不仅仅是 PropertyValuePropertyName.