Fluent验证WithMessage与SetValidator无法正常工作

时间:2015-10-23 13:53:39

标签: fluentvalidation

我已成功使用WithMessage,格式如下:

Certificate

这允许在错误消息中使用SomeOtherField的值。

我有一个更复杂的要求,我将SetValidator与我自己的自定义PropertyValidator一起使用,如下所示:

我认为可行的是:

RuleFor(p => p.MyField)
             .NotEmpty()                            
             .WithMessage("{0} is Required",
                                p => p.SomeOtherField
                            );

......但事实并非如此。验证失败后,我收到消息:

  

{0}无效

例如。 {0}未被替换

有什么想法吗?

here我发现PropertyNameResolver的概念听起来很合适,但我无法弄清楚如何配置它。该链接上的示例给出:

RuleFor(x => x.MyField)                
            .SetValidator(
                    new RemoteValidator(                            
                        "Validate", 
                        "Home", 
                        System.Web.Mvc.HttpVerbs.Post, 
                        "*.SomeOtherProperty1,*.SomeOtherProperty2")
            )
            .WithMessage("{0} is not valid",
                                p => p.MyOtherField
                            )
            ;

我正在使用Fluent Validations v5.6.2。

1 个答案:

答案 0 :(得分:0)

这实际上是我的自定义验证器的问题。

我正在关注this pattern,这使得它更加自定义并且包装了MVC的远程属性。

用更“正常”的自定义验证器替换它,这个位工作正常:

.WithMessage("{0} is not valid",
                            p => p.MyOtherField
                        )
        ;