C# 按条件设置 Fluent Validator

问题描述 投票:0回答:1

我正在尝试为“Address”设置验证器,具体取决于项目是否存在,但我想使用 RuleFor 和其他方便的方法,而不是使用“ValidationContext”手动记录每个错误,但似乎当我尝试通过“CustomAsync”来执行此操作时`,它只是被跳过,并且跳过了 `RequestAddressValidator` 的规则。
您对如何使 RequestAddressValidator 规则发挥作用有什么想法吗:
public class RequestModel
{
    public required string Id { get; init; }

    public Address? Address { get; init; }
}

public class Address
{
    public required string Line1 { get; init; }
    public required string Line2 { get; init; }
}

public class RequestAddressValidator: AbstractValidator<Address>
{
    public RequestAddressValidator()
    {
        RuleFor(x => x.Line1).NotEmpty();
        RuleFor(x => x.Line2).NotEmpty();
    }
}

public class RequestModelValidator: AbstractValidator<RequestModel>
{
    public RequestModelValidator(IApiClient apiClient)
    {
        RuleFor(x => x)
            .Custom((requestModel, context) =>
            {
                var item = apiClient.GetByIdAsync(requestModel.Id);

                if (item != null)
                {
                    RuleFor(x => x.Address).SetValidator(new RequestAddressValidator());
                }
            });
    }
}
c# asp.net validation .net-core fluentvalidation
1个回答
0
投票

您需要使用

CustomAsync

参见 异步验证

public class RequestModelValidator: AbstractValidator<RequestModel>
{
    public RequestModelValidator(IApiClient apiClient)
    {
        RuleFor(x => x)
            .CustomAsync(async (requestModel, context, cancellationToken) =>
            {
                var item = await apiClient.GetByIdAsync(requestModel.Id);

                if (item != null)
                {
                    RuleFor(x => x.Address).SetValidator(new RequestAddressValidator());
                }
            });
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.