例如,我有一个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
调用Validator时指定RuleSet通常这是在调用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
}
}
我知道在调用验证
时,可以将Ruleset作为参数传递我想知道是否可以使用 ValidateAndThrow 来完成?
答案 0 :(得分:2)
查看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);
}
}
}