嵌套属性的FluentValidation消息

Rom*_*ada 4 asp.net validation fluentvalidation

我有一个复杂属性的类:

public class A
{
    public B Prop { get; set; }
}

public class B
{
    public int Id { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我添加了一个验证器:

public class AValidator : AbstractValidator<A>
{
    public AValidator()
    {
        RuleFor(x => x.A.Id).NotEmpty().WithMessage("Please ensure you have selected the A object");            
    }
}
Run Code Online (Sandbox Code Playgroud)

但在A.Id的客户端验证期间,我仍然有一个默认的val消息:"'Id'不能为空".如何从验证器将其更改为我的字符串?

Ste*_*tes 9

这里有一个替代选项。在您的Startup类中配置 FluentValidation 时,您可以设置以下内容configuration.ImplicitlyValidateChildProperties = true;

所以完整的代码可能看起来像这样

services
    .AddMvc()
    .AddFluentValidation(configuration =>
        {
            ...
            configuration.ImplicitlyValidateChildProperties = true;
            ...
        })
Run Code Online (Sandbox Code Playgroud)

所以你仍然会有两个验证器,一个用于 class A,一个用于 class B,然后 classB将被验证。

该文件指出:

如果可以找到匹配的验证器,是否应该隐式验证子属性。默认情况下,这是 false,您应该使用 SetValidator 连接子验证器。

因此,将其设置为true意味着将验证子属性。


Ale*_* L. 7

您可以通过对嵌套对象使用自定义验证器来实现此目的:

public class AValidator : AbstractValidator<A>
{
    public AValidator()
    {
        RuleFor(x => x.B).NotNull().SetValidator(new BValidator());
    }

    class BValidator : AbstractValidator<B>
    {
        public BValidator()
        {
            RuleFor(x => x.Id).NotEmpty().WithMessage("Please ensure you have selected the B object");
        }
    }
}

public class A
{
    public B B { get; set; }
}

public class B
{
    public int Id { get; set; }
}
Run Code Online (Sandbox Code Playgroud)


t13*_*138 7

相当老的问题,但对于后代 - 您可以使用子验证器或定义内联子规则,如官方文档中所述:https ://fluidation.net/start#complex-properties