Is it possible to ignore a custom validation annotation to be ignored?
I am using Spring 4 and Hibernate 5
I have a user class with a password field with a custom validator.
I need to test it while the form binding should be 8 characters long and contain lowercase and uppercase letters and numbers.
When the user enters the password, it is valid, but it is invalid when I encode it.
So, is there a way for custom validation annotations to be ignored with persistence?
I know I can make another field for the plaintext password, or make a data transfer object, validate it, and then transfer the data to the user. But I'm interested in the ability to parameterize the annotation.
@Entity
@Table(name = "user")
public class User {
//other fields
@NotNull
@NotEmpty
@ValidPassword
@Column(name = "password", nullable = false, length = 60)
private String password;
//getters and setters
}
My validator
@Target({ TYPE, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = PasswordValidator.class)
@Documented
public @interface ValidPassword {
String message() default "Password is too short! Must be 8 digits and include lowercase, uppercase letters and numbers.";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
and
public class PasswordValidator implements ConstraintValidator<ValidPassword, String> {
private Pattern pattern;
private Matcher matcher;
private static final String PATTERN = "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{8,})";
@Override
public void initialize(ValidPassword constraintAnnotation) {
}
@Override
public boolean isValid(String password, ConstraintValidatorContext context) {
return (validate(password));
}
private boolean validate(String password) {
pattern = Pattern.compile(PATTERN);
matcher = pattern.matcher(password);
return matcher.matches();
}
}
Controller method
@RequestMapping(value = "/registeruser", method = RequestMethod.POST)
public String registerUser(@ModelAttribute("user") @Valid User user, BindingResult result, Model model) {
if (result.hasErrors()) {
model.addAttribute("errorSummary", result.getFieldErrors().stream()
.map(e -> e.getField() + " error - " + e.getDefaultMessage() + " ").collect(Collectors.toList()));
model.addAttribute("user", user);
} else {
User registered = null;
registered = createUserAccount(user, result);
if (registered == null) {
model.addAttribute("errorSummary", "User with this email already registered!");
model.addAttribute("user", user);
return "registration";
}
model.addAttribute("flashMessage", "User registered successfully!");
}
return "registration";
}
UserService implementation method (where I encode my password)
@Transactional
@Override
public User registerNewUserAccount(User user) throws EmailExistsException {
if (emailExist(user.getEmail())) {
throw new EmailExistsException("There is an account with that email address:" + user.getEmail());
}
if (user.getPassword() == null) {
user.setPassword(new BigInteger(130, new SecureRandom()).toString(32));
System.out.println("+++++++++++++++" + user.getPassword());
}
user.setPassword(passwordEncoder.encode(user.getPassword()));
user.setUserRole(new HashSet<UserRole>(1));
user.getUserRole().add(new UserRole(user, Constants.RoleType.USER.name()));
save(user);
return user;
}
source to share
By default, the check will be performed for all restrictions. Or you can specify Grouping restrictions
You can create a group by creating an interface:
interface FormValidationGroup{}
And annotate the field password
like this:
@ValidPassword(groups = FormValidationGroup.class)
private String password;
Documentation for Custom Constraints Annotation where parameter is mentioned groups
.
Hibernate Validator should now ignore the field password
if you don't specify a group to validate. To specify a group to validate a Spring MVC handler method parameter, use the Validated annotation instead Valid
. For example:.
String registerUser(@ModelAttribute @Validated(FormValidationGroup.class) User user,
BindingResult result, Model model) {
if (result.hasErrors()) {
source to share