Constraints
Every constraint the specification defines is in place, with the specification’s null semantics and applicable types, each mapped to one of rulii’s built-in validation rules. On top of them the library ships the constraints Hibernate Validator users know, and a set of its own.
Standard Constraints
Section titled “Standard Constraints”All 22 built-in Jakarta constraints: @AssertFalse, @AssertTrue, @DecimalMax, @DecimalMin, @Digits, @Email, @Future, @FutureOrPresent, @Max, @Min, @Negative, @NegativeOrZero, @NotBlank, @NotEmpty, @NotNull, @Null, @Past, @PastOrPresent, @Pattern, @Positive, @PositiveOrZero and @Size.
A few behave as Hibernate Validator does, which is a superset of the specification: @Min, @Max, @DecimalMin and @DecimalMax also accept double, float and CharSequence; @Email judges the domain part by shape alone, so user@localhost passes; the temporal constraints accept every java.time type including the chrono calendars.
Additional Constraints
Section titled “Additional Constraints”Under org.rulii.validation.beans.constraints, with the same simple names and attributes as their Hibernate Validator counterparts, so that changing the import is the whole migration. A message override written for the Hibernate key (org.hibernate.validator.constraints.Length.message) is honoured for them.
| Constraint | Checks | Backed by |
|---|---|---|
@Length(min, max) |
Character sequence length within bounds | Validators.size |
@Range(min, max) |
Number within bounds | Validators.min / max |
@URL(protocol, host, port, regexp) |
A URL, optionally with required parts | Validators.url |
@UUID |
Canonical UUID form, with version, variant and case options | Validators.uuid |
@CreditCardNumber |
Luhn check over a card number | Validators.luhnCheck |
@LuhnCheck, @Mod10Check, @Mod11Check |
Check-digit tests over a run of digits | Validators.luhnCheck / mod10Check / mod11Check |
@EAN |
EAN-13 or EAN-8 barcode number | Validators.ean |
@ISBN |
ISBN-10, ISBN-13 or either | Validators.isbn |
@UniqueElements |
A collection holds no element twice | Validators.uniqueElements |
@Normalized |
Unicode normalization form (NFC by default) | Validators.normalized |
@CodePointLength(min, max) |
Number of code points within bounds | Validators.codePointLength |
@DurationMin, @DurationMax (under constraints.time) |
A Duration against a bound, inclusive or exclusive |
Validators.durationMin / durationMax |
And rulii’s own, each backed by the rulii validator of the same name: @Alpha, @AlphaNumeric, @Ascii, @Numeric, @Decimal, @In, @StartsWith, @EndsWith, @LowerCase and @UpperCase.
import org.rulii.validation.beans.constraints.*;
public class Product {
@UUID String id;
@ISBN(type = ISBN.Type.ISBN_13) String isbn;
@URL(protocol = "https") String homepage;
@In({"NEW", "USED", "REFURBISHED"}) String condition;
@UniqueElements List<@NotBlank String> tags;}Your Own @Constraint Annotations
Section titled “Your Own @Constraint Annotations”A custom constraint with a ConstraintValidator runs unchanged: one instance per constraint occurrence, initialize once, isValid with the specification’s context. The validator becomes the condition of a rulii rule (ConstraintValidatorRule), and the constraint’s attributes become the rule’s parameters.
@Constraint(validatedBy = SkuValidator.class)@Target({FIELD, PARAMETER})@Retention(RUNTIME)public @interface Sku { String message() default "{com.acme.Sku.message}"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {};}
public class SkuValidator implements ConstraintValidator<Sku, String> { public boolean isValid(String value, ConstraintValidatorContext context) { return value == null || value.matches("[A-Z]{3}-\\d{4}"); }}The ConstraintValidatorContext supports custom templates, message parameters, expression variables and dynamic payloads. Unwrap it to RuliiConstraintValidatorContext for the provider-specific additions, which are the ones Hibernate Validator users know:
public boolean isValid(Quote value, ConstraintValidatorContext context) { RuliiConstraintValidatorContext ctx = context.unwrap(RuliiConstraintValidatorContext.class); ctx.addMessageParameter("limit", value.getLimit()); // renders as {limit} ctx.addExpressionVariable("over", value.getOverage()); // renders as ${over} ctx.disableDefaultConstraintViolation(); ctx.buildConstraintViolationWithTemplate("{com.acme.Quote.over}") .enableExpressionLanguage() .addPropertyNode("amount") .addConstraintViolation(); return false;}Composed constraints and @ReportAsSingleViolation work as specified. A validator that needs collaborators is created through the configured ConstraintValidatorFactory, which is backed by rulii’s ObjectFactory; with rulii-spring validators are Spring beans with injection.
A constraint can also be mapped to rulii rules directly, without a ConstraintValidator, through a ConstraintMapper. That is how the standard constraints are mapped and how to make an annotation of yours a rule that is listed, traced and reusable outside validation; see Constraints as rulii Rules.
Groups, Sequences and Conversion
Section titled “Groups, Sequences and Conversion”groups, group inheritance, @GroupSequence on a class (a redefined default) and on a sequence interface, @ConvertGroup, and the implicit grouping of constraints declared on an interface all work as specified.
public interface OnCreate {}public interface OnUpdate {}
@GroupSequence({Default.class, OnCreate.class})public interface CreateChecks {}
public class Order { @NotNull(groups = OnCreate.class) String reference; @NotNull(groups = {OnCreate.class, OnUpdate.class}) String code;
@Valid @ConvertGroup(from = OnCreate.class, to = Default.class) Customer customer;}
validator.validate(order, CreateChecks.class); // Default first, OnCreate only if Default passed@GroupSequenceProvider, a Hibernate Validator extension, has no equivalent. A sequence that depends on the object’s state is a decision, so it belongs in a rule: attach a RuleFlow with @Validate that reads the object and runs what applies. The flow sees the groups being processed as $groups.
Containers and Cascading
Section titled “Containers and Cascading”Type-use constraints and @Valid on List<@NotNull String>, Map<K, @Valid V>, Optional, OptionalInt, OptionalLong, OptionalDouble, arrays and your own containers through a ValueExtractor, registered on the builder or, on the bootstrap path, discovered through META-INF/services.
public class Shipment {
@Valid List<@NotNull Parcel> parcels;
Map<@NotBlank String, @Positive Integer> weights;
Optional<@Email String> contact;}Cascading follows @Valid through properties, containers, parameters and return values; a cycle is detected per validation call, so a shared object reached by two paths is reported once, as Hibernate Validator does. The TraversableResolver is consulted as specified; when Jakarta Persistence is on the classpath the default resolver does not cascade into unloaded entities.
Messages
Section titled “Messages”A ValidationMessages.properties at the root of the classpath overrides the defaults, with locale variants. {attribute} references, {key} lookups, ${validatedValue}, ${formatter.format(...)} and the escaping rules work as specified; EL needs an implementation on the classpath. A configured MessageInterpolator is called per violation with the specification’s context.
jakarta.validation.constraints.Size.message=length must be between {min} and {max} (was ${validatedValue.length()})com.acme.Sku.message=must be a SKU like ABC-1234The default texts are the specification’s Appendix B, with Hibernate’s wording for @Pattern (must match "{regexp}"). The library’s own defaults live in org/rulii/validation/beans/ValidationMessages.properties. Because the constraint’s attributes are also the rulii violation’s parameters, the same template works through rulii’s message resolution.
Severities
Section titled “Severities”A constraint may carry one of the payload markers Warning, Info or Fatal from org.rulii.validation.beans.payload to report at that severity instead of ERROR. The violation still appears in the result, with the severity on its rulii side:
@Size(max = 140, payload = Warning.class)String note;Hibernate Validator has no equivalent, so this is additive: a bean that uses it still validates elsewhere, where the payload is ignored.