Spring combine two validation annotations in one

I am using Spring + Hibernate + Spring-MVC .
I want to define a user constraint combining two other predefined validation annotations: @NotNull @Sizeas follows:

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

@NotNull
@Size(min=4)
public @interface JPasswordConstraint {
} // this is not correct. It just a suggestion.

and I want to use this annotation in my form models.

public class ChangePasswordForm {

  @NotNull
  private String currentPass;

  @JPasswordConstraint
  private String newPass;

  @JPasswordConstraint
  private String newPassConfirm;
}

UserController.java

@RequestMapping(value = "/pass", method = RequestMethod.POST)
public String pass2(Model model, @Valid @ModelAttribute("changePasswordForm") ChangePasswordForm form, BindingResult result) {
    model.addAttribute("changePasswordForm", form);
    try {
        userService.changePassword(form);
    } catch (Exception ex) {
        result.rejectValue(null, "error.objec", ex.getMessage());
        System.out.println(result);
    }
    if (!result.hasErrors()) {
        model.addAttribute("successMessage", "password changed successfully!");
    }
    return "user/pass";
}

But that will not work. It accepts passwords less than 4 characters.
How can I solve this problem?

+6
source share
2 answers

It's a bit late, but the method for combining validation annotations is described in

https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/?v=5.4#section-constraint-composition

, ,

@NotNull
@Size(min=4)
@Target({ METHOD, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = { })
@Documented
public @interface JPasswordConstraint {
    String message() default "Password is invalid";
    Class<?>[] groups() default { };
    Class<? extends Payload>[] payload() default { };
 }
+7

@ConstraintComposition

AND, @NotNull @Size,

@ConstraintComposition(OR)
0

Source: https://habr.com/ru/post/1614184/


All Articles