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());
}
});
}
}
您需要使用
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());
}
});
}
}