11 — Validation
RuleViolations & Severity
When validation rules fail, they add RuleViolation objects to a RuleViolations container. This section explains how to work with violations and severity levels.
Severity Levels
FATAL
Critical error. Should not proceed any further.
ERROR
Serious error. Action must be taken to fix it.
WARNING
Potential issue. Should be addressed at some point.
INFO
Informational message. No action required.
Working with RuleViolations
RuleViolations violations = new RuleViolations();
// Check for problems
violations.isEmpty(); // true if no violations
violations.hasErrors(); // true if any ERROR-level violations
violations.hasFatalErrors(); // true if any FATAL-level violations
violations.hasWarnings(); // true if any WARNING-level violations
violations.hasInfoMessages(); // true if any INFO-level violations
// Check for FATAL or ERROR combined
violations.hasSevereErrors(); // true if FATAL or ERROR exist
// Count by severity
long errorCount = violations.getErrorCount(Severity.ERROR);
long fatalCount = violations.getErrorCount(Severity.FATAL);
Accessing Individual Violations
// Get all violations as a list
List<RuleViolation> all = violations.getViolations();
// Get by index
RuleViolation first = violations.getViolation(0);
// Total count
int count = violations.size();
// Iterate
for (RuleViolation v : violations) {
System.out.println(v.getRuleName()); // "NotNullValidationRule"
System.out.println(v.getErrorCode()); // "notNullValidationRule.errorCode"
System.out.println(v.getSeverity()); // ERROR
System.out.println(v.getErrorMessage()); // "Value must not be null."
System.out.println(v.getParameters()); // {} additional params
}
Adding Violations Manually
You can add violations yourself in custom rules or otherwise-actions:
RuleViolations violations = new RuleViolations();
// Quick add (defaults to Severity.ERROR)
violations.add("myRule", "error.001");
// With all details
violations.add("myRule", "error.002", Severity.WARNING, "Something looks off");
// Using the builder
violations.add(RuleViolation.builder().build(
"myRule", "error.003", "Detailed error message"));
Complete Example
// Build a validation RuleSet
RuleSet<?> ruleSet = RuleSet.builder()
.with("UserValidation")
.rule(Rule.builder().build(new NotNullValidationRule("name")))
.rule(Rule.builder().build(new EmailValidationRule("email")))
.build();
// Run with invalid data
RuleViolations violations = new RuleViolations();
ruleSet.run(name -> null, email -> "not-an-email", ruleViolations -> violations);
// Check results
if (violations.hasSevereErrors()) {
System.out.println("Validation failed with " + violations.size() + " error(s):");
for (RuleViolation v : violations) {
System.out.println(" [" + v.getSeverity() + "] " + v.getErrorMessage());
}
}