Skip to content

Validating Beans

A bean annotated for Bean Validation needs no change. This page shows the three ways to validate one: the standard Jakarta bootstrap, the rulii builder, and inside a rulii RuleContext you already have.

public class Order {
@NotNull @Size(min = 2, max = 5)
String code;
@NotNull(groups = OnCreate.class)
String reference;
@Valid
Customer customer;
@Positive
int quantity = 1;
}

With this library as the only provider on the classpath, the Jakarta bootstrap hands out a BeanValidator, and so does every framework that bootstraps through Validation:

Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
Set<ConstraintViolation<Order>> violations = validator.validate(order);

Provider-specific options go through Validation.byProvider, which returns the library’s RuliiConfiguration:

Validator validator = Validation.byProvider(RuliiValidationProvider.class)
.configure()
.registry(registry)
.failFast(true)
.buildValidatorFactory()
.getValidator();

The same validator, built the rulii way, when you do not need the bootstrap:

BeanValidator validator = BeanValidator.builder()
.registry(registry)
.build();
BeanValidationResult<Order> result = validator.validate(order, OnCreate.class);

BeanValidationResult is both the specification’s Set<ConstraintViolation<T>> and the owner of the rulii BeanRuleViolations, so code written against either model reads it:

for (ConstraintViolation<Order> violation : result) {
System.out.println(violation.getPropertyPath() + " " + violation.getMessage());
}
RuleViolations violations = result.getRuleViolations();

Every violation is a BeanRuleViolation: a rulii RuleViolation (rule name, error code, severity, message, parameters) and a ConstraintViolation (property path, invalid value, root and leaf bean, constraint descriptor) at once. The constraint’s attributes are the violation’s parameters, so getParameterValues() of a @Size violation holds min and max as numbers.

validateIn runs the bean’s rules inside a RuleContext you own. Annotation rules, your own rules and the trace share one execution, and the violations land in the context’s RuleViolations:

RuleContext context = RuleContext.builder().with(bindings).registry(registry).build();
RuleViolations violations = validator.validateIn(context, order);

Inside validateIn rulii’s own exception model applies: a failure is wrapped in an UnrulyException, as everywhere else in rulii, rather than in a ValidationException.

validateProperty and validateValue have the semantics the specification gives them. Groups are passed as with any provider, and @GroupSequence and @ConvertGroup are honoured:

// one property of a live object
validator.validateProperty(order, "code");
// a value that is not on an object yet
validator.validateValue(Order.class, "code", "AB");
// a group, a sequence, or several
validator.validate(order, OnCreate.class);
validator.validate(order, OrderChecks.class); // an @GroupSequence interface

forExecutables() returns the ExecutableValidator with all four methods. Interception stays with your framework: Spring’s method validation drives the ExecutableValidator of the configured Validator, so it works with this one.

public class OrderService {
public Receipt place(@NotNull @Valid Order order, @Min(1) int copies) { ... }
}
ExecutableValidator executables = validator.forExecutables();
Method place = OrderService.class.getMethod("place", Order.class, int.class);
Set<ConstraintViolation<OrderService>> violations =
executables.validateParameters(service, place, new Object[] { order, 0 });

Parameter names come from the configured ParameterNameProvider; the default tries rulii’s @Param, then reflection, then the compiled bytecode, so real names come back even without -parameters. The rulii-side ExecutableBeanValidator adds validateParametersIn and validateReturnValueIn for an existing RuleContext.

The specification’s API throws the specification’s exceptions:

  • Declaration problems are found when a class is first read for validation and raise ConstraintDeclarationException, ConstraintDefinitionException, UnexpectedTypeException, GroupDefinitionException or ValueExtractorDefinitionException, through subclasses that name the problem.
  • Failures inside validation, in a ConstraintValidator, a MessageInterpolator, a ValueExtractor, a TraversableResolver or a getter, reach the caller as a ValidationException: ConstraintValidatorException, MessageInterpolationException, TraversableResolverException, InaccessiblePropertyException, or BeanValidationException for anything else. A ValidationException thrown by your own code passes through unchanged.
  • A @Validate name that resolves to nothing raises ValidateRuleNotFoundException; a bad @Expr raises ExprDeclarationException naming the element and the script.

Because every constraint is a rulii rule, the usual rulii tooling sees it. A Tracer configured on the context options records every constraint rule that ran, and the rulii explorer lists validated beans member by member, opens the rule built for each constraint, draws the cascades between beans and the @Validate rules they run, and flags a @Validate name nothing is registered under (rulii.explorer.beans.enabled=true).