Overview
The Validator class is the central component of the library that facilitates validation of String values by chaining a series of rules. It provides both direct instantiation and a Builder pattern for creating complex validation chains.
Class Declaration
public class Validator implements Cloneable
Constructors
Default Constructor
Creates a new empty Validator instance.
Static Methods
setMessages
public static void setMessages(Messages messages)
Sets the default error messages for all predefined validation rules.
Custom messages implementation. If null, the method returns without making changes.
Example:
Validator.setMessages(new MessagesEs()); // Set Spanish messages
getMessages
public static Messages getMessages()
Returns the current Messages instance being used for default error messages.
Returns: The active Messages implementation
validOrFail
public static void validOrFail(Object obj) throws InvalidEvaluationException
Validates an object’s String fields using annotation-based validation rules.
The object to validate. All String fields with validation annotations will be checked.
Throws: InvalidEvaluationException if any field fails validation
Supported Annotations:
@Required
@Length
@MinLength
@MaxLength
@RangeLength
@Email
@Number
@RegExp
@Compare
@Date
@ExpirationDate
@MinAge
@Name
- And all other validation annotations
Example:
public class User {
@Required
@Email
private String email;
@MinLength(min = 8)
private String password;
@Compare(compareWith = "password")
private String confirmPassword;
}
User user = new User();
Validator.validOrFail(user); // Throws InvalidEvaluationException if invalid
Instance Methods
isValid
public boolean isValid(String evaluate)
Validates that a String meets all configured rules.
The String to validate against all rules
Returns: true if validation passes, false otherwise
Note: If validation fails and an onInvalidEvaluation handler is set, it will be invoked with the error message.
Example:
Validator validator = new Validator.Builder()
.build();
validator.required()
.build();
validator.email();
if (validator.isValid("[email protected]")) {
System.out.println("Valid email");
}
validOrFail (Instance)
public void validOrFail(String key, String evaluate) throws InvalidEvaluationException
Validates a String against all rules, throwing an exception if validation fails.
Identifier for the String being validated (used in exception)
Throws: InvalidEvaluationException with the field key, value, and error message
Example:
try {
validator.validOrFail("email", userInput);
} catch (InvalidEvaluationException e) {
System.out.println("Field: " + e.getKey());
System.out.println("Error: " + e.getMessage());
}
isMatch
public boolean isMatch(String evaluate, String compare)
Validates that two Strings match AND that they meet all configured rules.
The primary String to validate
The String to compare against
Returns: true if both strings match and pass all rules, false otherwise
Note: If the comparison fails or validation fails, the onInvalidEvaluation handler will be invoked.
Example:
Validator passwordValidator = new Validator();
passwordValidator.minLength(8);
passwordValidator.mustContainOne("!@#$%");
passwordValidator.setNotMatchMessage("Passwords do not match");
if (passwordValidator.isMatch(password, confirmPassword)) {
System.out.println("Passwords match and are valid");
}
compareOrFail
public void compareOrFail(String key, String evaluate, String compare) throws InvalidEvaluationException
Validates that two Strings match and meet all rules, throwing an exception on failure.
Identifier for the field being validated
The primary String to validate
The String to compare against
Throws: InvalidEvaluationException if strings don’t match or validation fails
setNotMatchMessage
public void setNotMatchMessage(String message)
Sets the custom error message for comparison failures in isMatch() and compareOrFail().
The error message to display when Strings don’t match
rule
public void rule(String message, Validate validate)
Adds a custom validation rule to the validator.
Error message to display if validation fails
Functional interface that takes a String and returns true if valid
Example:
validator.rule("Must not be 'admin'", value -> !value.equals("admin"));
validator.rule("Must start with uppercase", value ->
Character.isUpperCase(value.charAt(0))
);
onInvalidEvaluation
public void onInvalidEvaluation(OnInvalidEvaluation onInvalidEvaluation)
Sets an event handler that is invoked when validation fails.
onInvalidEvaluation
OnInvalidEvaluation
required
Functional interface that receives the error message when validation fails
Example:
validator.onInvalidEvaluation(errorMessage -> {
System.err.println("Validation error: " + errorMessage);
// Show in UI, log, etc.
});
copy
Creates a shallow copy of the Validator instance.
Returns: A new Validator instance with the same rules and configuration, or null if cloning fails
Example:
Validator baseValidator = new Validator();
baseValidator.required();
baseValidator.minLength(5);
Validator emailValidator = baseValidator.copy();
emailValidator.email();
Validator phoneValidator = baseValidator.copy();
phoneValidator.numberPattern("+xx (xxx) xxx-xxxx");
Predefined Rules
The Validator class provides numerous predefined validation rules. Each rule has two overloads:
- One accepting a custom error message
- One using the default message from the Messages configuration
See the individual rule documentation pages:
Builder Pattern
The Validator.Builder class provides a fluent API for constructing validators.
Creating a Builder
Validator validator = new Validator.Builder()
.required()
.email()
.maxLength(100)
.onInvalidEvaluation(error -> System.err.println(error))
.build();
Builder Methods
All validation rule methods are available on the Builder and return Builder for chaining.
setNotMatchMessage
public Builder setNotMatchMessage(String message)
Sets the error message for comparison failures.
Returns: The Builder instance for chaining
onInvalidEvaluation
public Builder onInvalidEvaluation(OnInvalidEvaluation onInvalidEvaluation)
Sets the validation failure handler.
Returns: The Builder instance for chaining
build
Constructs and returns the configured Validator instance.
Returns: A new Validator with all configured rules
Complete Builder Example
Validator passwordValidator = new Validator.Builder()
.required("Password is required")
.minLength(8, "Password must be at least 8 characters")
.mustContainOne("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "Must contain uppercase letter")
.mustContainOne("abcdefghijklmnopqrstuvwxyz", "Must contain lowercase letter")
.mustContainOne("0123456789", "Must contain a number")
.mustContainOne("!@#$%^&*", "Must contain a special character")
.onInvalidEvaluation(error -> displayError(error))
.build();
try {
passwordValidator.validOrFail("password", userPassword);
} catch (InvalidEvaluationException e) {
// Handle validation failure
}
Usage Patterns
Pattern 1: Direct Instantiation
Validator validator = new Validator.Builder()
.build();
validator.required()
.build();
validator.email();
validator.maxLength(255);
if (validator.isValid(email)) {
// Process valid email
}
Pattern 2: Builder Pattern
Validator validator = new Validator.Builder()
.required()
.email()
.maxLength(255)
.build();
Pattern 3: Annotation-Based
public class SignupForm {
@Required
@Email
@MaxLength(max = 255)
private String email;
@Required
@MinLength(min = 8)
@MustContainOne(alphabet = "0123456789")
private String password;
}
SignupForm form = new SignupForm();
Validator.validOrFail(form);
Pattern 4: Reusable Validators
// Create base validator
Validator baseStringValidator = new Validator.Builder()
.required()
.maxLength(500)
.build();
// Copy and extend for specific use cases
Validator usernameValidator = baseStringValidator.copy();
usernameValidator.minLength(3);
usernameValidator.onlyAlphanumeric();
Validator nameValidator = baseStringValidator.copy();
nameValidator.name();
See Also