比如我有一个Person Validator
public class PersonValidator : AbstractValidator<Person> {
public PersonValidator() {
RuleSet("Names", () => {
RuleFor(x => x.Surname).NotNull();
RuleFor(x => x.Forename).NotNull();
});
RuleFor(x => x.Id).NotEqual(0);
}
}
如何在使用 ValidateAndThrow 调用验证器时指定规则集
通常这是在调用 ValidateAndThrow 时完成的
public class ActionClass
{
private readonly IValidator<Person> _validator;
public ActionClass(IValidator<Person> validator)
{
_validator=validator
}
public void ValidateForExample(Person model)
{
_validator.ValidateAndThrow(model)
//When there is no error I can continue with my operations
}
}
我知道在调用Validate时可以将规则集作为参数传递
我想知道是否也可以使用 ValidateAndThrow 来完成?
最佳答案
查看 source :
public static void ValidateAndThrow<T>(this IValidator<T> validator, T instance)
{
var result = validator.Validate(instance);
if(! result.IsValid)
{
throw new ValidationException(result.Errors);
}
}
默认情况下不允许这样做,但是没有什么可以阻止您创建自己的小扩展方法,该方法也采用规则集名称,如下所示:
public static class ValidationExtensions
{
public static void ValidateAndThrow<T>(this IValidator<T> validator, T instance, string ruleSet)
{
var result = validator.Validate(instance, ruleSet: ruleSet);
if (!result.IsValid)
{
throw new ValidationException(result.Errors);
}
}
}
关于c# - 流畅验证 : Is it possible to add a RuleSet while invoking a validator using ValidateAndThrow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33556922/