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;}Through the Standard Bootstrap
Section titled “Through the Standard Bootstrap”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();Through the Builder
Section titled “Through the Builder”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.
Inside an Existing rulii Context
Section titled “Inside an Existing rulii Context”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.
Properties, Values and Groups
Section titled “Properties, Values and Groups”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 objectvalidator.validateProperty(order, "code");
// a value that is not on an object yetvalidator.validateValue(Order.class, "code", "AB");
// a group, a sequence, or severalvalidator.validate(order, OnCreate.class);validator.validate(order, OrderChecks.class); // an @GroupSequence interfaceMethods and Constructors
Section titled “Methods and Constructors”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.
Exceptions
Section titled “Exceptions”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,GroupDefinitionExceptionorValueExtractorDefinitionException, through subclasses that name the problem. - Failures inside validation, in a
ConstraintValidator, aMessageInterpolator, aValueExtractor, aTraversableResolveror a getter, reach the caller as aValidationException:ConstraintValidatorException,MessageInterpolationException,TraversableResolverException,InaccessiblePropertyException, orBeanValidationExceptionfor anything else. AValidationExceptionthrown by your own code passes through unchanged. - A
@Validatename that resolves to nothing raisesValidateRuleNotFoundException; a bad@ExprraisesExprDeclarationExceptionnaming the element and the script.
Seeing It
Section titled “Seeing It”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).