我们正在使用流利验证(与服务堆栈)来验证我们的请求DTO。我们最近扩展了我们的框架以接受“修补程序”请求,这意味着我们现在只有在包含被验证字段的修补程序时才需要应用验证。
我们使用这样的扩展方法完成了这一工作:
RuleFor(dto => dto.FirstName).Length(1,30)).WhenFieldInPatch((MyRequest dto)=>dto.FirstName);
RuleFor(dto => dto.MiddleName).Length(1,30)).WhenFieldInPatch((MyRequest dto)=>dto.MiddleName);
RuleFor(dto => dto.LastName).Length(1,30)).WhenFieldInPatch((MyRequest dto)=>dto.LastName);这意味着我们可以对POST/PUT或修补程序运行相同的验证。
我一直在寻找一种连接到fluent验证框架的方法,例如我们不需要在我们验证的每一行上复制.WhenFieldInPatch()规则,但是还没有找到一种很好的方法来做到这一点。
我尝试了以下几点:
我是错过了什么,还是在尝试不可能的事?
谢谢
发布于 2020-04-30 17:00:34
当我需要分享流利的验证逻辑时,我会使用扩展方法,下面是TechStacks的共享扩展方法的一个例子,例如:
public static class ValidatorUtils
{
public static bool IsValidUrl(string arg) => Uri.TryCreate(arg, UriKind.Absolute, out _);
public static string InvalidUrlMessage = "Invalid URL";
public static IRuleBuilderOptions<T, string> OptionalUrl<T>(
this IRuleBuilderInitial<T, string> propertyRule)
{
return propertyRule
.Length(0, UrlMaxLength)
.Must(IsValidUrl)
.When(x => !string.IsNullOrEmpty(x as string))
.WithMessage(InvalidUrlMessage);
}
}以及共享它们的一些例子:
public class CreatePostValidator : AbstractValidator<CreatePost>
{
public CreatePostValidator()
{
RuleSet(ApplyTo.Post, () =>
{
RuleFor(x => x.Url).OptionalUrl();
});
}
}
public class UpdatePostValidator : AbstractValidator<UpdatePost>
{
public UpdatePostValidator()
{
RuleSet(ApplyTo.Put, () =>
{
RuleFor(x => x.Url).OptionalUrl();
});
}
}https://stackoverflow.com/questions/61528512
复制相似问题