gdogaru
gdogaru

Reputation: 521

Set custom invalidValue in Jersey ConstraintValidator error message

I have a Jersey Validator implemented like below, which I use on the request object.

When I get the error response I get the whole object in the "invalidValue" field.

I want to be able to set the invalid value to a single field from MyRequest, not the whole object. This is because I want my validation logic to depend on 2 fields but only one to be reported as invalid.

@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = {MyValidation.Validator.class})
public @interface MyValidation {
    String message() default "{my.message}";

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

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

    class Validator implements ConstraintValidator<EmailUnique, MyRequest> {

        @Override
        public void initialize(final MyValidation email) {
        }

        @Override
        public boolean isValid(final MyRequest mr, final  ConstraintValidatorContext constraintValidatorContext) {
           return mr.getField()!= null; //or some more complicated logic
        }
    }
}

The response looks like:

[{
    "message": "nice message",
    "messageTemplate": "{my.message}",
    "path": "....",
    "invalidValue": "MyRequest@149e88d9" <--- need to be able to specify the value here
}]

Upvotes: 1

Views: 698

Answers (1)

Clint Eastwood
Clint Eastwood

Reputation: 5698

I think that implementing MyRequest#toString() will solve your problem.

Note: I have rephrased my original answer to be a statement rather than a question.

Upvotes: 1

Related Questions