Javax Validation extra error on validation fail

254 views Asked by At

I have an 'Answer' object that may be one of many types of answers (email, phone number, name...) I am writing a custom validator to handle the validation and regardless of the answer type the answer text is stored in a single 'value' param.

Here is what i have got:

Annotation definition:

@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = AnswerValidator.class)

public @interface ValidateAnswerEmail {
    String message() default "";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

Validator

public class AnswerValidator implements ConstraintValidator<ValidateAnswerEmail, Answer> {

    @Override
    public boolean isValid(Answer answer, ConstraintValidatorContext context) {
        boolean success = true;
        // validation #1
        // validation #2
        // validation #3

        return success;
    }
}

My issue is that i am getting back an extra validation failed message if one of them fails. This appears to be coming from the return success returning false and then using the annotations String message() default ""; as the error message.

Wondering if i can suppress that validation violation message and only return the ones that i add to the ConstraintValidatorContext?

No Spring, Vanilla Java. Thanks in advance.

Here is the message

Constraint violations: 
 (1) Kind: PARAMETER
 parameter index: 0
 message: Email address: some@[email protected] is not a valid email address
 root bean: org.company.crs.api.AnswerResource@42475403
 property path: updateAnswer.arg0
 constraint: @org.company.crs.validator.ValidateAnswerEmail(message="", groups={}, payload={})
 (2) Kind: PARAMETER
 parameter index: 0
 message: 
 root bean: org.company.crs.api.AnswerResource@42475403
 property path: updateAnswer.arg0
 constraint: @org.company.crs.validator.ValidateAnswerEmail(message="", groups={}, payload={})
1

There are 1 answers

0
Bend On

You are looking for: context.disableDefaultConstraintViolation();