Home > Software engineering >  Missing Validation Error Message of Java ConstraintValidator on class level
Missing Validation Error Message of Java ConstraintValidator on class level

Time:11-08

I have a java spring boot project, where I want to validate the matching passwords and show the error in the json response.

public interface SecurityCredentialsRequest {
    String getPassword();
    String getPasswordConfirmation();
}

@Getter
@Setter
@PasswordConfirmation
public class UserSignUpRequest implements SecurityCredentialsRequest {
    //...
    @UniqueEmailUserSignup
    private String email;

    private String password;
    private String passwordConfirmation;
}

Validator:

@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = PasswordConfirmationValidator.class)
@Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE})
@Documented
public @interface PasswordConfirmation {
    String message() default "The password and its confirmation do not match.";

    Class[] groups() default {};

    Class[] payload() default {};
}

@Component
public class PasswordConfirmationValidator implements ConstraintValidator<PasswordConfirmation, SecurityCredentialsRequest> {
    @Override
    public void initialize (final PasswordConfirmation constraintAnnotation) {
    }

    @Override
    public boolean isValid(SecurityCredentialsRequest securityCredentialsRequest, ConstraintValidatorContext constraintValidatorContext) {
        String password = securityCredentialsRequest.getPassword();
        String passwordConfirmation = securityCredentialsRequest.getPasswordConfirmation();

        return password != null && password.equals(passwordConfirmation);
    }
}

The validator on the class level is called, but no error message is contained in the response payload. When I use the other custom validator that is used on an attribute (@UniqueEmailUserSignup), the error message looks like the following. The message for the passwordConfirmation is missing though.

{
  "timestamp": "2021-11-05T14:57:56.2488041",
  "errors": [
    {
      "code": 775,
      "field": "email",
      "message": "An account with the specified email already exists."
    }
  ]
}

The entity is validated via the @Valid annotation in the controller function.

@PostMapping(path = PATH)
public ResponseEntity<UserAccountDataResponse> doUserSignUp(@RequestBody @Valid UserSignUpRequest userSignUpRequest) {
    //...
}

How can I ensure, that also the error message of the custom ConstraintValidator is included in the error response?

CodePudding user response:

I found the solution. It was missing the property path and therefore, it was ignored. Adding this solved the issue:

constraintValidatorContext.buildConstraintViolationWithTemplate(constraintValidatorContext.getDefaultConstraintMessageTemplate())
    .addPropertyNode("passwordConfirmation").addConstraintViolation();
  • Related