0

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@User@gmail.com 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={})
Bend
  • 304
  • 1
  • 2
  • 15
  • Why not make Answer an abstract class/interface and require that subclasses/implementations implement an isValid() method? – Bohemian Apr 03 '23 at 19:55
  • Because in the DB and the UI they are just an 'Answer', so it doesn't make a whole lot of sense to parse incoming REST requests into Answer subtypes, only to save them back to the DB as an answer anyway, and vice versa. Especially since we dont have precedent for that in this repo as it stands now. And with this one exception, the API layer doesn't care about what type of answer this is, just that it is an answer. So, while you probably have a technically correct solution, i think it is overkill for this. – Bend Apr 03 '23 at 20:03

1 Answers1

0

You are looking for: context.disableDefaultConstraintViolation();

Bend
  • 304
  • 1
  • 2
  • 15