I am making a custom password validator. The annotation:
@Documented
@Constraint(validatedBy = PasswordConstraint.class)
@Target({ElementType.FIELD})
public @interface Password {
String message() default "";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
The constraint which checks the length of the password and if password contains letters, digits and symbols.
public class PasswordConstraint implements ConstraintValidator<Password, String> {
@Override
public void initialize(Password password) {
ConstraintValidator.super.initialize(password);
}
@Override
public boolean isValid(String password, ConstraintValidatorContext context) {
int min = 8;
String symbols = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~";
if (password.length() < min) {
return false;
}
if (password.chars().noneMatch(Character::isAlphabetic))
return false;
else {
boolean lower = password.chars().anyMatch(Character::isLowerCase);
boolean upper = password.chars().anyMatch(Character::isUpperCase);
if (!(lower && upper))
return false;
}
if (password.chars().noneMatch(Character::isDigit))
return false;
return password.chars().anyMatch(c -> symbols.indexOf(c) != 0);
}
}
How do I dynamically change the message for each case?