Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring class level validation and Thymeleaf

I am learning Spring Framework and Thymeleaf. I have known how to display field error by using something like ${#fields.errors("xx")}. However, I get stuck about how to display object error message in Thymeleaf.

Here is my UserForm class:

@PasswordMatches
public class UserForm {
    @NotNull
    @NotEmpty
    private String username;
    @NotNull
    @NotEmpty
    private String password;
    @NotNull
    @NotEmpty
    private String matchingPassword;
    @NotNull
    @NotEmpty
    @ValidEmail
    private String email;

    /* setter and getter methods */

Here is my PasswordMatches annotation:

@Target({ElementType.TYPE, ElementType.FIELD, ElementType.ANNOTATION_TYPE}) 
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = PasswordMatchesValidator.class)
@Documented
public @interface PasswordMatches { 
    String message() default "Passwords don't match";
    Class<?>[] groups() default {}; 
    Class<? extends Payload>[] payload() default {};
}

class PasswordMatchesValidator implements ConstraintValidator<PasswordMatches, Object> {  
    @Override
    public void initialize(PasswordMatches constraintAnnotation) {       
    }

    @Override
    public boolean isValid(Object obj, ConstraintValidatorContext context){   
        UserDto user = (UserDto) obj;
        return user.getPassword().equals(user.getMatchingPassword());    
  }     
}

Here is my Controller method:

@RequestMapping(value="/registration", method=RequestMethod.POST)
public ModelAndView registerUserAccount(@ModelAttribute("user") @Valid UserForm userForm,
          BindingResult result, WebRequest request, Errors errors) {
    if (!result.hasErrors()) {
        return new ModelAndView("registerSuccess");
    }
    else {
        return new ModelAndView("registration", "user", userForm);
    }
}

Now here is my problem: If the password field and confirmPass field doesn't match, how can I get the default error message returned by the class level annotation in Thymeleaf?

like image 644
DCestLaVie Avatar asked Jun 10 '18 16:06

DCestLaVie


People also ask

How do I add validation to Thymeleaf?

To set a custom message for any validation constraint, you can use the message option: @NotEmpty(message = "Field can't be empty!) private String field; You can simply write these messages out in your model, like this.

Is Thymeleaf fully integrated with Spring?

It provides full integration with Spring Framework. It applies a set of transformations to template files in order to display data or text produced by the application. It is appropriate for serving XHTML/HTML5 in web applications. The goal of Thymeleaf is to provide a stylish and well-formed way of creating templates.

Is Thymeleaf supported by Spring MVC?

Thymeleaf offers a set of Spring integrations that allow you to use it as a fully-featured substitute for JSP in Spring MVC applications.


1 Answers

I know this is old post but I also encountered this problem and here is the soulution (maybe it will also help someone else): Modify PasswordMatchesValidator to this:

class PasswordMatchesValidator implements ConstraintValidator<PasswordMatches, Object> {  
@Override
public void initialize(PasswordMatches constraintAnnotation) {       
}

@Override
public boolean isValid(Object obj, ConstraintValidatorContext context){   
    UserDto user = (UserDto) obj;
    boolean isValid = user.getPassword().equals(user.getMatchingPassword());
    if(!isValid){
         context.disableDefaultConstraintViolation();
        context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate())
                .addPropertyNode( "matchingPassword" ).addConstraintViolation();
    }
    return isValid;

}

it will bind the validation result to your 'matchingPassword' attribute. So in your thymeleaf template us it like this:

${#fields.errors("matchingPassword")}
like image 125
a4dev92 Avatar answered Oct 17 '22 16:10

a4dev92