Custom Validation Rules
Extend the ValidationRule base class to create your own domain-specific validators. Each custom rule defines its error code, severity, error message, and validation logic using @Given and @Otherwise annotations.
ValidationRule Base Class
Section titled “ValidationRule Base Class”The ValidationRule base class provides the following properties:
- errorCode Unique identifier for the validation error
- severity FATAL, ERROR, WARNING, or INFO
- errorMessage Template message with placeholders
- defaultMessage Fallback message when template fails
Example: Phone Number Validator
Section titled “Example: Phone Number Validator”@Rule(name = "PhoneNumberValidationRule")public class PhoneNumberValidationRule extends ValidationRule {
private final String fieldName;
public PhoneNumberValidationRule(String fieldName) { super("phoneNumber.invalid", Severity.ERROR, "${fieldName} must be a valid phone number.", "Value must be a valid phone number."); this.fieldName = fieldName; }
@Given public boolean isValid(@Param("fieldName") String value) { if (value == null) return true; // Let NotNull handle nulls return value.matches("^\\+?[1-9]\\d{1,14}$"); }
@Otherwise public void otherwise(RuleViolations ruleViolations) { ruleViolations.add(getRuleName(), getErrorCode(), getSeverity(), getErrorMessage()); }}Using the Custom Rule
Section titled “Using the Custom Rule”Rule rule = Rule.builder().build(new PhoneNumberValidationRule("phone"));
// Run through a RuleFlow — the recommended wayRuleFlow<RuleViolations> flow = RuleFlow.builder() .name("PhoneValidationFlow") .bind(ruleViolations -> new RuleViolations()) .run(rule) .<RuleViolations>returning(function((RuleViolations ruleViolations) -> ruleViolations)) .build();
RuleViolations violations = flow.run(phone -> "not-a-phone");
violations.hasErrors(); // trueLambda-Based Validation: SuppliedValidationRule
Section titled “Lambda-Based Validation: SuppliedValidationRule”For simpler cases, use SuppliedValidationRule to create a validator from a lambda without writing a full class:
Condition check = condition((String email) -> email != null && email.contains("@company.com"));
SuppliedValidationRule rule = new SuppliedValidationRule( check, "corporate.email", Severity.ERROR, "Must use a corporate email", "Must use a corporate email");(new in 2.1.0) SuppliedValidationRule.getCondition() exposes the supplied condition. When building through the fluent ValidationRuleBuilder (Rule.builder().validationRule(name, condition)), 2.1.0 fixes build() so it no longer drops a description set on the builder, and the builder gains category(String), tags(String...) and source(SourceDefinition) — see Introspection & Metadata.
Extra Violation Parameters & Descriptions (new in 2.2.0)
Section titled “Extra Violation Parameters & Descriptions (new in 2.2.0)”Every value validation rule built through a ValueValidationRuleBuilder (the builders behind Validators, and your own subclasses) can carry extra violation parameters: param(name, value) and params(Map<String, ?>). Every violation of the rule reports them, so a message template can refer to values the rule itself does not know — a constraint’s attributes under the names the constraint gives them, say.
Rule rule = Validators.size(Validators.binding("code"), 3, 20) .param("field", "Order.code") .errorMessage("${field} must be between ${min} and ${max} characters") .build();
// Parameter order on every violation: the validated value first,// then the extra params, then the rule's own (min, max, ...)The validated value is always the first parameter and wins on a shared name; so do the rule’s own parameters, reported after the extras. ValueValidationRule.getParameters() answers what was configured. Nothing changes for a rule built without them.
Rules also say what they check. ValueValidationRule.describe() names the value and the rule’s own parameters — code size must be between 3 and 20, email must not be null — and a value rule built without a description now gets this text instead of the class-level @Description. An explicit description still wins. ValueValidationRuleBuilder.describe() returns the same text for the configuration so far, before build().
Severity Levels
Section titled “Severity Levels”Customize the severity of your validation rules to control how violations are treated:
| Severity | Description |
|---|---|
| Severity.FATAL | Critical error that should halt processing |
| Severity.ERROR | Validation failure that must be corrected |
| Severity.WARNING | Potential issue that should be reviewed |
| Severity.INFO | Informational notice, not a failure |
Customizing Error Codes & Messages
Section titled “Customizing Error Codes & Messages”Error codes should follow a dot-separated naming convention (e.g., phoneNumber.invalid, email.corporate). Error messages support template placeholders like ${fieldName} that are resolved at runtime, while the default message serves as a fallback when template resolution fails.