Built-in Validation Rules
rulii ships with 48 ready-to-use validation rules (eleven of them new in 2.2.0). Each one checks a specific constraint and adds a RuleViolation when the check fails. The recommended way to create them is through the Validators static factory, introduced in 1.2.0.
The Validators Factory
Section titled “The Validators Factory”Validators provides one static factory method per built-in rule. Each method returns a fluent builder so you can customize the error code, severity, and message before calling .build().
Pass a value supplier as the first argument. Use binding("fieldName") to look up a named binding from the RuleContext at execution time, or value(someObject) to supply a constant.
import static org.rulii.validation.rules.Validators.*;
// Simple: validate the "name" binding is not nullRule notNull = notNull(binding("name")).build();
// With custom error detailsRule notNull = notNull(binding("name")) .errorCode("ERR-001") .severity(Severity.FATAL) .message("Name is required!") .build();
// Range rule with parametersRule sizeCheck = size(binding("name"), 2, 50).build();
// Run itRuleViolations violations = new RuleViolations();notNull.run(name -> null, ruleViolations -> violations);violations.hasErrors(); // true — name was null(new in 2.1.0) The validation rule builders also accept category(String), tags(String...) and source(SourceDefinition) — descriptive metadata recorded on the rule’s definition, never read at execution time (see Introspection & Metadata). ValueValidationRule.getValueName() — the binding name of the value a rule validates — is now public.
Examples
Section titled “Examples”The examples below show the most common patterns: custom error codes and messages, supplying a constant with value(), and rules that accept additional parameters such as bounds or a regex pattern.
import static org.rulii.validation.rules.Validators.*;
// Custom error code and messageRule usernameRequired = notBlank(binding("username")) .errorCode("USER-001") .message("Username must not be blank.") .build();
// Custom error code with the default message kept (omit .message())Rule emailValid = email(binding("email")) .errorCode("USER-002") .build();
// value() — validate a constant or already-resolved object, not a bindingString currentStatus = resolveStatus();Rule statusCheck = notNull(value(currentStatus)) .errorCode("STATUS-001") .message("Status must be set.") .build();
// size — String / Collection / Array length within [min, max]Rule nameLength = size(binding("name"), 2, 50) .errorCode("USER-003") .message("Name must be between 2 and 50 characters.") .build();
// min / max — numeric boundsRule ageMin = min(binding("age"), 18) .errorCode("USER-004") .message("Age must be at least 18.") .build();
Rule quantityMax = max(binding("quantity"), 100) .errorCode("ORDER-001") .build();
// decimalMin / decimalMax — decimal / BigDecimal boundsRule priceMin = decimalMin(binding("price"), 0.01) .errorCode("PRICE-001") .message("Price must be greater than zero.") .build();
Rule discountMax = decimalMax(binding("discount"), 0.99) .errorCode("PRICE-002") .build();
// digits — at most N integer digits and M fractional digitsRule amount = digits(binding("amount"), 8, 2) .errorCode("AMOUNT-001") .message("Amount must have at most 8 integer digits and 2 decimal places.") .build();
// pattern — match a regular expressionRule postalCode = pattern(binding("postalCode"), "\\d{5}(-\\d{4})?") .errorCode("ADDR-001") .message("Postal code must be in ZIP or ZIP+4 format.") .build();
// positive / positiveOrZero — sign checksRule positiveScore = positive(binding("score")) .errorCode("SCORE-001") .build();
// notEmpty with value() — check a list resolved outside the contextList<String> roles = loadRoles(userId);Rule hasRoles = notEmpty(value(roles)) .errorCode("AUTH-001") .message("User must have at least one role assigned.") .build();Validation Rules in a RuleSet
Section titled “Validation Rules in a RuleSet”Predefined validation rules are plain Rule instances and compose into a RuleSet the same way any other rule does. Every rule that fires a violation automatically writes it to the ruleViolations binding, so all violations are collected in a single pass.
User registration
import static org.rulii.validation.rules.Validators.*;
RuleSet<?> registrationRules = RuleSet.builder() .with("UserRegistration") .rule(notBlank(binding("username")) .errorCode("REG-001").message("Username is required.").build()) .rule(size(binding("username"), 3, 20) .errorCode("REG-002").message("Username must be 3–20 characters.").build()) .rule(alphaNumeric(binding("username")) .errorCode("REG-003").message("Username may only contain letters and digits.").build()) .rule(notBlank(binding("email")) .errorCode("REG-004").message("Email is required.").build()) .rule(email(binding("email")) .errorCode("REG-005").message("Email address is not valid.").build()) .rule(min(binding("age"), 18) .errorCode("REG-006").message("You must be at least 18 years old.").build()) .build();
// Run through a RuleFlow — returns the violations directlyRuleFlow<RuleViolations> registrationFlow = RuleFlow.builder() .name("UserRegistrationFlow") .bind(ruleViolations -> new RuleViolations()) .run(registrationRules) .<RuleViolations>returning(function((RuleViolations ruleViolations) -> ruleViolations)) .build();
RuleViolations violations = registrationFlow.run( username -> "jo", email -> "not-an-email", age -> 16);
// REG-002, REG-005, REG-006 will be presentviolations.hasErrors(); // trueOrder line validation
import static org.rulii.validation.rules.Validators.*;
RuleSet<?> orderLineRules = RuleSet.builder() .with("OrderLineValidation") .rule(notBlank(binding("productCode")) .errorCode("ORD-001").message("Product code is required.").build()) .rule(min(binding("quantity"), 1) .errorCode("ORD-002").message("Quantity must be at least 1.").build()) .rule(max(binding("quantity"), 999) .errorCode("ORD-003").message("Quantity cannot exceed 999.").build()) .rule(decimalMin(binding("unitPrice"), 0.01) .errorCode("ORD-004").message("Unit price must be greater than zero.").build()) .rule(digits(binding("unitPrice"), 8, 2) .errorCode("ORD-005").message("Unit price must have at most 8 integer and 2 decimal digits.").build()) .build();
// Run through a RuleFlow — returns the violations directlyRuleFlow<RuleViolations> orderLineFlow = RuleFlow.builder() .name("OrderLineFlow") .bind(ruleViolations -> new RuleViolations()) .run(orderLineRules) .<RuleViolations>returning(function((RuleViolations ruleViolations) -> ruleViolations)) .build();
RuleViolations violations = orderLineFlow.run( productCode -> "SKU-42", quantity -> 0, unitPrice -> 12.5);
// ORD-002 fires — quantity 0 is below the minimum of 1violations.hasErrors(); // trueIterating violations
// Check overall resultif (violations.hasErrors()) { for (RuleViolation v : violations) { System.out.printf("[%s] %s%n", v.getErrorCode(), v.getErrorMessage()); }}
// Or collect error codes onlyList<String> codes = violations.stream() .map(RuleViolation::getErrorCode) .collect(Collectors.toList());What’s New in 2.2.0
Section titled “What’s New in 2.2.0”2.2.0 adds eleven validation rules covering constraints Bean Validation users know from other providers — they back the constraint annotations of rulii-bean-validation — and gives several existing rules new options. Each new rule has a builder and a Validators entry:
import static org.rulii.validation.rules.Validators.*;
RuleSet<RuleViolations> catalogChecks = RuleSet.<RuleViolations>builder() .with("CatalogChecks") // canonical 36-character UUID, version 4 only, lower-case hex digits .rule(uuid(binding("productId")).versions(4).letterCase(UuidValidationRule.LetterCase.LOWER_CASE).build()) // ISBN-10 or ISBN-13 by length; separators ignored .rule(isbn(binding("isbn")).type(IsbnValidationRule.Type.ISBN_13).build()) // EAN-13 / EAN-8 barcode and a Luhn check digit (credit-card style) .rule(ean(binding("barcode")).build()) .rule(luhnCheck(binding("cardNumber")).ignoreNonDigitCharacters(true).build()) // no element twice; NFC-normalized; 3–20 code points (supplementary characters count once) .rule(uniqueElements(binding("tags")).build()) .rule(normalized(binding("title")).form(Normalizer.Form.NFC).build()) .rule(codePointLength(binding("title"), 3, 20).build()) // a Duration against a bound, inclusive by default .rule(durationMax(binding("leadTime"), Duration.ofDays(30)).inclusive(false).build()) // existing rules, new options .rule(url(binding("homepage")).protocol("https").port(443).build()) .rule(email(binding("contact")).anyDomain().pattern(".*@acme\\.com").build()) .resultExtractor(function((RuleViolations ruleViolations) -> ruleViolations)) .build();- Rules describe themselves.
ValueValidationRule.describe()says what a rule checks, naming the value and its own parameters (code size must be between 3 and 20,email must not be null). A rule built without a description now gets this text instead of the class-level@Description; an explicit description still wins.ValueValidationRuleBuilder.describe()returns it for the configuration so far. urloptions.protocol(..),host(..),port(..)and aregexp(..)(withflags(..)) the URL must also match; the parts are read withjava.net.URI. Without options it validates as before.emailoptions.anyDomain()judges the domain part by shape alone (host-name labels or an IP literal, no top-level-domain registry, local and single-label hosts allowed), as the Bean Validation reference implementation does; off by default.pattern(..)(withflags(..)) is a regex the whole address must also match, reported as thepatternviolation parameter — one rule and one violation for “well-formed and matching”.- Bounds and digits.
decimalMin/decimalMaxreportinclusiveas a violation parameter besidemin/max, so a message can tell an inclusive bound from an exclusive one.digits(value, 0, 2)now accepts zero integral digits (passes0.12, fails1.2); it refused anything below one before.DecimalMaxValidationRule.DEFAULT_MESSAGEread “must not be less than or equal to”, the inverse of the check; it now reads “must not be greater than”. - More calendars.
past,pastOrPresent,futureandfutureOrPresentaccept thejava.time.chronodatesHijrahDate,JapaneseDate,MinguoDateandThaiBuddhistDate, compared with the date of the configured clock in their own calendar. - Supported types are public. Every validation rule exposes
public static final List<Class<?>> SUPPORTED_TYPES(an immutableList.of), so a constraint can be checked against a declared property type before any rule instance exists;getSupportedTypes()andisSupported(Class)on the rules are unchanged.
Direct Instantiation is Not Supported
Section titled “Direct Instantiation is Not Supported”As of 1.2.0, predefined validation rule classes (NotNullValidationRule, EmailValidationRule, etc.) are no longer intended to be instantiated directly. Their constructors are not part of the public API and may change between releases.
Always create built-in rules through the Validators static factory. This keeps your code decoupled from the underlying implementation classes and ensures you get the correct builder configuration every time.
import static org.rulii.validation.rules.Validators.*;
// Correct — use the factoryRule r = notNull(binding("email")).build();
// Incorrect — do not instantiate directly// Rule r = new NotNullValidationRule(...);Available Validators
Section titled “Available Validators”| Factory Method | What It Checks |
|---|---|
| notNull(fn) | Value is not null |
| isNull(fn) | Value is null |
| notEmpty(fn) | Collection / String / Array is not empty |
| notBlank(fn) | String is not blank (not null, not empty, not whitespace) |
| blank(fn) | Value is blank (null or whitespace-only) |
| size(fn, min, max) | String / Collection / Array size is within [min, max] |
| min(fn, min) | Numeric value ≥ min |
| max(fn, max) | Numeric value ≤ max |
| decimalMin(fn, min) | Decimal value ≥ min |
| decimalMax(fn, max) | Decimal value ≤ max |
| positive(fn) | Number > 0 |
| positiveOrZero(fn) | Number ≥ 0 |
| negative(fn) | Number < 0 |
| negativeOrZero(fn) | Number ≤ 0 |
| digits(fn, maxInt, maxFrac) | At most maxInt integer digits and maxFrac fractional digits |
| email(fn) | Valid e-mail address format |
| url(fn) | Valid URL format |
| pattern(fn, regex) | Matches the given regular expression |
| assertTrue(fn) | Value is true |
| assertFalse(fn) | Value is false |
| assertEquals(fn, expected) | Value equals the expected value |
| assertNotEquals(fn, unexpected) | Value does not equal the given value |
| future(fn) | Date / time value is in the future |
| futureOrPresent(fn) | Date / time value is now or in the future |
| past(fn) | Date / time value is in the past |
| pastOrPresent(fn) | Date / time value is now or in the past |
| alpha(fn) | String contains only alphabetic characters |
| alphaNumeric(fn) | String contains only alphanumeric characters |
| ascii(fn) | String contains only ASCII characters |
| numeric(fn) | String contains only digit characters |
| decimal(fn) | String is a valid decimal number; leading or trailing spaces only with allowSpace() (from 2.3.0; up to 2.2.0 they were always accepted) |
| lowerCase(fn) | String is all lower-case |
| upperCase(fn) | String is all upper-case |
| startsWith(fn, prefixes…) | String starts with one of the given prefixes |
| endsWith(fn, suffixes…) | String ends with one of the given suffixes |
| in(fn, collection) | Value is contained in the given collection |
| fileExists(fn) | Value is a path to an existing file |
| uuid(fn) (new in 2.2.0) | Canonical 36-character UUID; options for the empty string, the nil UUID, accepted versions(..) / variants(..) and letterCase(..) |
| uniqueElements(fn) (new in 2.2.0) | Collection holds no element twice |
| normalized(fn) (new in 2.2.0) | Character sequence is in a Unicode normalization form(..) (NFC by default) |
| codePointLength(fn, min, max) (new in 2.2.0) | Number of code points is within [min, max], optionally after normalization(..); supplementary characters count once |
| durationMin(fn, min) (new in 2.2.0) | Duration ≥ min (inclusive(false) for >) |
| durationMax(fn, max) (new in 2.2.0) | Duration ≤ max (inclusive(false) for <) |
| luhnCheck(fn) (new in 2.2.0) | Luhn check digit over a run of digits located by startIndex / endIndex / checkDigitIndex; non-digits dropped or rejected (ignoreNonDigitCharacters) |
| mod10Check(fn) (new in 2.2.0) | Modulo 10 check digit with multiplier and weight, same index options as luhnCheck |
| mod11Check(fn) (new in 2.2.0) | Modulo 11 check digit with threshold, treatCheck10As / treatCheck11As and processingDirection; the arithmetic is public in ModCheck |
| ean(fn) (new in 2.2.0) | EAN-13 or EAN-8 barcode number (type(..)) |
| isbn(fn) (new in 2.2.0) | ISBN-10, ISBN-13 or either by length (type(..)), separators ignored |