问题
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