Custom validator message: Throwing exception in implementation of ConstraintValidator cause UnexpectedException

If you want to display custom message try this piece of code.

@Override
public boolean isValid(String userName, ConstraintValidatorContext context) {
    if (userService.findByUserName(userName) != null) {
        context.disableDefaultConstraintViolation();
        context
            .buildConstraintViolationWithTemplate("User " + userName + "already exists!")
            .addConstraintViolation();
        return false;
    }
    return true;
}

Leave a Comment

tech