我想知道是否可以在 FluentValidations 验证器中为一些可选参数更新验证模型,以防这些参数无效?
这是一些代码:
public class Customer
{
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
}
public class CustomerValidator : AbstractValidator<Customer>
{
public CustomerValidator()
{
RuleFor(customer => customer.FirstName).NotNull().Length(5, 100);
RuleFor(customer => customer.LastName).NotNull().Length(5, 100);
RuleFor(customer => customer.MiddleName).Length(5, 100).When(c => string.IsNullOrWhiteSpace(c.MiddleName));
}
}
我是这样使用它的:
Customer customer = new Customer { FirstName = "first name", LastName = "last name" };
CustomerValidator validator = new CustomerValidator();
var result = validator.Validate(customer);
Console.WriteLine(result.IsValid);
所以在我的例子中,我想在中间名无效时将其设置为 null,并在变量中保存警告,但仍将模型视为有效。
最佳答案
更新传递给验证的对象不是一个好主意,Validator 应该只验证输入实体,并返回验证结果,仅此而已。我建议你有两个验证器。一个用于业务关键规则,一个用于警告,因此如果第一个验证器返回该模型无效,您将返回结果,如果没有严重错误,则您将验证警告,然后您可以决定是否继续操作您的模型! 例如
public class Customer
{
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
}
public class CustomerCriticalValidator : AbstractValidator<Customer>
{
public CustomerValidator()
{
RuleFor(customer => customer.FirstName).NotNull().Length(5, 100);
RuleFor(customer => customer.LastName).NotNull().Length(5, 100);
}
}
public class CustomerWarningValidator : AbstractValidator<Customer>
{
public CustomerValidator()
{
RuleFor(customer => customer.MiddleName).Length(5, 100).When(c => string.IsNullOrWhiteSpace(c.MiddleName));
}
}
然后在代码中
Customer customer = new Customer();
CustomerCriticalValidator criticalValidator = new CustomerCriticalValidator();
CustomerWarningValidator warningValidator = new CustomerWarningValidator();
var validationResult = criticalValidator.Validate(customer);
if (validationResult.IsValid)
{
var result = warningValidator.Validate(customer);
if (!result.IsValid)
{
//DO what you need with customer
}
}
关于c# - FluentValidation:更新验证器内部一些可选属性的验证模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58064363/