Skip to content

Why I'd use rulii to validate incoming data

Every system I’ve worked on has to validate incoming data. It doesn’t matter whether it arrives at a REST controller or on a Kafka topic. Before you act on it, you check it.

Normally we reach for Bean Validation. A few annotations on the class, @NotNull here, @Size there, and for a while that’s enough.

Then the more complicated cases turn up. A date that has to come after another date. An order that can’t go over the customer’s credit limit. Cross-field edits, and plain business rules. That’s where the annotations run out, and that’s where I’d use rulii.

A constraint looks at one value. The moment a check needs two fields, Bean Validation asks you for a class-level annotation and a ConstraintValidator class to go with it. That’s two new types to say “the ship date can’t be before the order date”.

A check that needs to ask a service something is worse. You can do it, with another annotation and a validator that has the service injected. In practice nobody does. It ends up in the service method, after the “validation” has already passed. The rule is back in the business tier, which is where we came in.

Nothing changes here. rulii-bean-validation is a Bean Validation provider, so the annotations already on your classes run as they are.

public class OrderRequest {
@NotBlank
private String customerId;
@NotNull @Positive
private BigDecimal total;
@NotNull
private LocalDate orderDate;
private LocalDate shipDate;
private String purchaseOrder;
// getters and setters
}

@Expr puts the condition where the field is. No validator class and no new annotation.

@ExprDefaults(lang = "jakarta-el")
public class OrderRequest {
// ...
@Expr(value = "#{orderDate == null || !shipDate.isBefore(orderDate)}",
errorCode = "order.shipDate",
message = "Ship date is before the order date")
private LocalDate shipDate;
}

An order has rules that aren’t about its fields at all:

  • the customer’s account has to be active;
  • the total can’t go over the customer’s credit limit;
  • an order of 10,000 or more needs a purchase order number.

None of that belongs on the class. It depends on who the customer is today, and it will change. So the class only says which rules apply, by name:

@Validate("orderRules")
public class OrderRequest {
// ...
}

Two of those rules need to ask a service, so they’re classes. Spring injects what they need:

@Rule(name = "withinCreditLimit")
public class WithinCreditLimit {
private final Customers customers;
public WithinCreditLimit(Customers customers) {
this.customers = customers;
}
@Given
public boolean withinLimit(String customerId, BigDecimal total) {
return total.compareTo(customers.creditLimit(customerId)) <= 0;
}
@Otherwise
public void report(RuleViolations violations) {
violations.add("withinCreditLimit", "order.creditLimit",
Severity.ERROR, "Order total is over the credit limit");
}
}

The rule gets the fields of the request by name. CustomerIsActive looks the same, with a different question. You can test either one on its own, with a fake Customers and no web layer in sight.

orderRules is a rule set: the rules, the order they run in, and when to stop.

@Configuration
public class OrderRulesConfig {
private static final BigDecimal PO_THRESHOLD = new BigDecimal("10000");
@Bean
public RuleSet<?> orderRules(@Qualifier("customerIsActive") Rule customerIsActive,
@Qualifier("withinCreditLimit") Rule withinCreditLimit) {
return RuleSet.builder()
.with("orderRules", "What an order has to satisfy beyond its fields")
.preCondition(condition((String customerId, BigDecimal total) ->
customerId != null && total != null))
.stopCondition(stopWhenOneFails())
.rule(customerIsActive)
.rule(withinCreditLimit)
.rule(assertTrue(function((BigDecimal total, String purchaseOrder) ->
total.compareTo(PO_THRESHOLD) < 0 || purchaseOrder != null))
.errorCode("order.purchaseOrder")
.message("Orders of 10,000 or more need a purchase order")
.build())
.build();
}
}

It reads top to bottom. Don’t bother unless there’s a customer and a total. Stop at the first rule that fails, because there’s no point checking the credit limit of a closed account. The third rule only looks at the data, so it’s a lambda.

If you’d rather the rules lived outside the build, this is the same rule set:

<r:ruleset name="orderRules"
description="What an order has to satisfy beyond its fields"
pre-condition="#ctx.customerId != null and #ctx.total != null"
stop-condition="#ctx.ruleSetStatus.anyFail">
<r:rules>
<r:bean-ref name="customerIsActive"/>
<r:bean-ref name="withinCreditLimit"/>
<r:validationRule name="largeOrderNeedsPurchaseOrder"
errorCode="order.purchaseOrder"
errorMessage="Orders of 10,000 or more need a purchase order"
given="#ctx.total &lt; 10000 or #ctx.purchaseOrder != null"/>
</r:rules>
</r:ruleset>

The two rules that need a service are still the classes above, referenced by name. The purchase order rule is written out, threshold and all. When the business decides it’s 5,000, that’s a change to a file, not a rebuild. XML Rule Definitions has the rest of the grammar.

OrderRequest doesn’t know or care which of the two you chose. It asks for orderRules.

The constraints, the cross-field check and the rule set report through the same validator:

Set<ConstraintViolation<OrderRequest>> violations = validator.validate(request);
A negative total, shipped the day before it was ordered
[total] must be greater than 0
[shipDate] Ship date is before the order date
A customer whose account is closed
Customer account is not active
9,000 against a credit limit of 5,000
Order total is over the credit limit
25,000 with no purchase order
Orders of 10,000 or more need a purchase order

In a Spring Boot application with rulii-spring and rulii-bean-validation, the Validator bean is rulii’s, so a controller doesn’t change:

@PostMapping("/orders")
public Receipt place(@Valid @RequestBody OrderRequest request) {
return orders.place(request);
}

A Kafka listener uses the same validator and the same rules:

@KafkaListener(topics = "orders")
public void onOrder(OrderRequest request) {
Set<ConstraintViolation<OrderRequest>> violations = validator.validate(request);
if (!violations.isEmpty()) {
deadLetters.send(request, violations);
return;
}
orders.place(request);
}

One class says what a valid order is, and it holds wherever the order comes from.

Hibernate Validator checks annotations, and it does that well. It even has @ScriptAssert for a condition across two fields. What it doesn’t have is anywhere to put a business rule: something with a name, an order and a stopping point, that you can test on its own and change without touching the class. In a Hibernate project those become hand-written validator classes, or if statements in a service.

So I’d move, and it costs less than you’d think.

Add rulii-bean-validation beside rulii-spring and it becomes the application’s validator. Your annotations stay as they are. The constraints Hibernate adds on top, @Length, @Range, @URL and the rest, are there under the same names. Your own ConstraintValidator classes keep running. Then, when you’re ready, exclude hibernate-validator from the validation starter, and it’s gone.

What you get for it is one engine. The annotations and the business rules run in the same place and report the same way. Rules are attached by name and changed without touching the class. And every constraint on every bean shows up in the explorer as a rule you can read.

Now the part you should know. Hibernate Validator is the reference implementation and it’s certified. rulii-bean-validation isn’t, and it doesn’t run the TCK. The differences are written down, chapter by chapter, and none of the known ones changes the outcome for an ordinary bean. If certification is a requirement where you work, stay where you are.

If it isn’t, the migration guide is a checklist of seven steps, and one property puts you back if I turn out to be wrong.

Start with Validating Beans.