c# - FluentValidation:更新验证器内部一些可选属性的验证模型

标签 c# fluentvalidation

我想知道是否可以在 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/

相关文章:

c# - 比较并识别特定位置的位置和值并打印

C# 通用接口(interface)白名单候选过滤

c# - 如何在 LINQ 中执行以下操作

c# - 流利验证 : set custom message on custom validation

c# - 发布后 Clickonce 部署更改更新位置?

c# - 递归创建自定义复杂对象

c# - 使用数据库的 FluentValidation 唯一名称验证

regex - 如何使用 FluentValidation 创建强密码?

c# - 使用 fluentvalidation 检查另一条规则

c# - 通过属性实现验证的基本问题?请指导我