Password validation is critical for application security. The Validator library provides powerful tools to enforce password strength requirements through character composition rules.
Create a validator that enforces multiple character type requirements:
import io.github.ApamateSoft.validator.Validator;import static io.github.ApamateSoft.validator.utils.Alphabets.*;Validator strongPassword = new Validator.Builder() .required("Password is required") .minLength(12, "Password must be at least 12 characters") .mustContainMin(3, ALPHA_LOWERCASE, "At least 3 lowercase letters required") .mustContainMin(3, ALPHA_UPPERCASE, "At least 3 uppercase letters required") .mustContainMin(3, NUMBER, "At least 3 numbers required") .mustContainMin(3, "@~_/", "At least 3 special characters (@~_/) required") .build();
The mustContainMin(min, alphabet, message) rule validates that the string contains at least min characters from the specified alphabet.
Here’s a complete password change form implementation:
import io.github.ApamateSoft.validator.Validator;import static io.github.ApamateSoft.validator.utils.Alphabets.*;public class PasswordChangeForm { private final Validator currentPasswordValidator = new Validator.Builder() .required("Current password is required") .build(); private final Validator newPasswordValidator = new Validator.Builder() .required("New password is required") .minLength(12, "Must be at least 12 characters") .mustContainMin(3, ALPHA_LOWERCASE) .mustContainMin(3, ALPHA_UPPERCASE) .mustContainMin(3, NUMBER) .mustContainOne("@#$%^&*") .setNotMatchMessage("Passwords do not match") .build(); private String currentPassword = ""; private String newPassword = ""; private String confirmNewPassword = ""; public PasswordChangeForm() { currentPasswordValidator.onInvalidEvaluation(msg -> displayError("current", msg)); newPasswordValidator.onInvalidEvaluation(msg -> displayError("new", msg)); } public void submit() { if (!currentPasswordValidator.isValid(currentPassword)) return; if (!newPasswordValidator.isMatch(newPassword, confirmNewPassword)) return; // All validations passed updatePassword(currentPassword, newPassword); } private void displayError(String field, String message) { System.err.println(field + " error: " + message); }}
Never log or display actual password values in error messages. The InvalidEvaluationException contains the password value in getValue(), but you should only use the getMessage() and getKey() for error handling.