How to pass RuleSet to FluentValidation constructor?

雨燕双飞 提交于 2019-12-12 18:36:57

问题


How can I pass name of specific RuleSet to inner validator (for Orders)?

I would like it to be applied conditionally, based on property available in outer validator (for Clients).

validator.Validate(client, ruleSet: "Production");

public class ClientValidator : AbstractValidator<Client>
{
    public ClientValidator()
    {
        RuleSet("Production", () =>
        {
            RuleFor(client => client.Orders)
                .SetCollectionValidator(new OrderValidator());

            When(client => client.IsVIP, () => {
                RuleFor(client => client.Orders)
                    .SetCollectionValidator(new OrderValidator());
                    //.SetCollectionValidator(new OrderValidator("VIPClient"));
            });                    
        });
    }
}

public class OrderValidator : AbstractValidator<Order>
{
    public OrderValidator()
    {
        RuleSet("Production", () =>
        {
            RuleFor(x => x.Items)
                .NotEmpty();
        });

        RuleSet("VIPClient", () =>
        {
            RuleFor(x => x.Discount)
                .GreaterThan(0);
        });
    }
}

Ok, I can do custom method, like example below, but wondering, if there is more elegant way.

validator.Validate(client, ruleSet: "Production");

public class ClientValidator : AbstractValidator<Client>
{
    public ClientValidator()
    {
        RuleSet("Production", () =>
        {
            RuleFor(client => client.Orders)
                .SetCollectionValidator(new OrderValidator());

            When(client => client.IsVIP, () => {
                RuleFor(client => client.Orders).Must((client, orders) =>
                    HaveDiscount(orders));
            });                    
        });
    }

    private static bool HaveDiscount(IEnumerable<Order> orders)
    {
        foreach (var order in orders)
        {
            if (order.Discount <= 0)
            {
                return false;
            }
        }
        return true;
    }
}

来源:https://stackoverflow.com/questions/35291718/how-to-pass-ruleset-to-fluentvalidation-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!