如何使用 FluentValidator 验证多个属性是否为 null?
有没有一种方法可以流畅地验证多个属性是否为空?
例如,在不使用 Fluentvalidator 的情况下,可以通过实现 IValidatableObject 来实现这一点。
public class Request : IValidatableObject
{
public int Id { get; init; }
public string Property1 { get; init; }
public string Property2 { get; init; }
public string Property3 { get; init; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (Property1 == null && Property2 == null && Property3 == null)
{
yield return new ValidationResult("Some message");
}
}
}
我找到了一种通过覆盖 Validate 来使用 FluentValidator 的方法,但这不是创建 FluentValidator 的方式。
public class RequestValidator : AbstractValidator<Request>
{
public override FluentValidation.Results.ValidationResult Validate(ValidationContext<Request> context)
{
if (context.InstanceToValidate.Property1 is null &&
context.InstanceToValidate.Property2 is null &&
context.InstanceToValidate.Property3 is null)
{
return new FluentValidation.Results.ValidationResult(new[]
{
new ValidationFailure("", "Custom message")
});
}
return new FluentValidation.Results.ValidationResult();
}
}
Is there a way to validate for null more than one properties in a fluent manner?
For example, without using Fluentvalidator, this may be possible by implementing IValidatableObject.
public class Request : IValidatableObject
{
public int Id { get; init; }
public string Property1 { get; init; }
public string Property2 { get; init; }
public string Property3 { get; init; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (Property1 == null && Property2 == null && Property3 == null)
{
yield return new ValidationResult("Some message");
}
}
}
I found a way to use FluentValidator via override Validate, but this is not the way FluentValidator was created for.
public class RequestValidator : AbstractValidator<Request>
{
public override FluentValidation.Results.ValidationResult Validate(ValidationContext<Request> context)
{
if (context.InstanceToValidate.Property1 is null &&
context.InstanceToValidate.Property2 is null &&
context.InstanceToValidate.Property3 is null)
{
return new FluentValidation.Results.ValidationResult(new[]
{
new ValidationFailure("", "Custom message")
});
}
return new FluentValidation.Results.ValidationResult();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一种可能的解决方案:
One possible solution:
另一种方法/风格,我发现对我来说更具可读性,是:
在它们是对象而不是原始类型的情况下,您可以执行类似的操作
Another way/style to do it, which I found little more readable to me, is:
In the case where they're objects instead of primitive types, you can do something like