Cross-Field Validation with Rules, RuleSets & RuleFlows
Validation that looks at more than one value is where annotations run out. Three tools, from the narrowest to the widest, and none of them needs a ConstraintValidator class or a class-level annotation of its own.
An Invariant: @Expr
Section titled “An Invariant: @Expr”One line on the class, no validator class, no registration. Covered in full on the previous page.
@Expr(value = "#{end == null || end.isAfter(start)}", errorCode = "trip.end")public class Trip { ... }A Rule: Write It in Java, Attach It by Name
Section titled “A Rule: Write It in Java, Attach It by Name”A rulii rule receives the bean’s properties as parameters, by name, and reports through the same RuleViolations the constraints use. Nothing in it mentions Bean Validation, so it is testable on its own and reusable outside validation:
@Rule@Description("The deposit covers the minimum for the room category.")public class DepositRule {
@PreCondition public boolean check(BigDecimal deposit, RoomCategory category) { return deposit != null && category != null; }
@Given public boolean isValid(BigDecimal deposit, RoomCategory category) { return deposit.compareTo(category.minimumDeposit()) >= 0; }
@Otherwise public void otherwise(BigDecimal deposit, RoomCategory category, RuleViolations violations) { violations.add(RuleViolation.builder().with("depositRule", "booking.deposit") .errorMessage("deposit " + deposit + " is below the minimum " + category.minimumDeposit()) .build()); }}RuleRegistry registry = RuleRegistry.builder() .register(Rule.builder().build(DepositRule.class)) .build();@Validate("depositRule")public class Booking { @NotNull BigDecimal deposit; @NotNull RoomCategory category;}The violation reports at the bean with the rule’s error code and message, next to the constraint violations. The rule runs after the constraints of its group step; a missing value is still handed to it as null, which is what the precondition is for, as in any rulii rule. On a property the rule also receives $value; on a method, the arguments by parameter name.
Declaration-Site Context: @Bind
Section titled “Declaration-Site Context: @Bind”One registered rule, parameterised per site. @Bind binds a fact about the declaration beside the properties, for every rule and script that runs there. See @Bind for the attributes.
@Validate("withinLimit") @Bind(name = "limit", value = "2", type = Integer.class)public class TableBooking { @NotNull Integer seats; }
@Validate("withinLimit") @Bind(name = "limit", value = "500", type = Integer.class)public class HallBooking { @NotNull Integer seats; }A Rule Set or a Flow: When the Logic Has Shape
Section titled “A Rule Set or a Flow: When the Logic Has Shape”Group the rules of a context in a RuleSet, or orchestrate them in a RuleFlow that branches, loops over items, stops early or runs checks in parallel. The flow sees the same scope as a rule: properties by name, $this, $root, $groups:
RuleFlow<?> orderRules = RuleFlow.builder() .name("orderRules") .run(creditRules) .when(condition((Customer customer) -> customer.isWholesale()), body -> body .run(wholesaleLimits)) .forEach(function((List<Item> items) -> items), "item", body -> body .run(itemAvailabilityRule)) .build();@Validate("orderRules")public class Order { ... }Register the flow under its name and the bean picks it up on its next validation. Replace what is registered under the name and the next validation runs the new logic: no change to the bean, no rebuild of the validator. With a MutableRuleRegistry that can happen while the application runs.
Scripted Rules
Section titled “Scripted Rules”A rule in the registry can be a script, in any language rulii knows, so a condition a domain expert maintains can live outside the compiled code and still be attached with @Validate:
Rule weekendRule = Rule.builder().name("noWeekendDelivery") .given(Condition.builder().build(Script.builder().with("jakarta-el", "#{deliveryDate.dayOfWeek.value < 6}").build())) .otherwise(action((RuleViolations violations) -> violations.add("noWeekendDelivery", "order.delivery.weekend"))) .build();Running Validation Inside Your Own Flow
Section titled “Running Validation Inside Your Own Flow”The direction also works the other way round. validateIn runs a bean’s rules inside a context you own, and getRuleFlow(Class) hands you the self-contained flow the library built for a class, to embed as a step in a flow of your own:
RuleFlow<?> checkout = RuleFlow.builder() .name("checkout") .run(validator.getRuleFlow(Order.class)) // the annotation rules, as one step .run(pricingRules) .run(fraudScreen) .build();The validation step, the pricing rules and the fraud screen then share one context, one set of bindings, one RuleViolations and one trace. See Constraints as rulii Rules for what the flow contains.
Choosing between them. An invariant of the data: @Expr. A decision that can change: a rule in the registry, attached with @Validate. Several decisions with ordering, branching or iteration: a RuleFlow, attached the same way.