0

Basically, I've created a custom annotation cross-field validation with a validator implementing ConstraintValidator.

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = SomeValidator.class)
@Documented
public @interface SomeAnnotation {
   String message() default "{javax.validation.constraints.NotNull.message}";

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

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

Validator implementation is pretty basic - it checks if some fields are empty (or not) according to a specific, selected entity type. The JSON error message returned by the server contains correct paths to variables with errors, but - unfortunately - it completely ignores the message I pass, replacing it with CustomAnnotationClass.entityClassInCamelCase.path.to.variable. I even tried using plain strings (without { }) or default message codes (for example, from @NotNull, that works for other fields) with no luck.

This is the code I use to set the message:

constraintValidatorContext.buildConstraintViolationWithTemplate(getMessage()).addPropertyNode("someField").addPropertyNode("id")
                      .addConstraintViolation();

(The only difference between other fields is the number of nodes and the method invocation that returns a string, but since I have no problem with the variable paths and ALL messages are ignored, I think it's irrelevant.)

A (slightly modified) example of returned JSON:

{"fieldErrors":[{"path":"someField.id","message":"MyAnnotationClass.someEntity.someField.id"}]}

Is this an incorrect way to set the message or am I missing some configurations?

4
  • Try to check BindingResults' error to see which paths are used and specify them
    – StanislavL
    Apr 24, 2015 at 5:27
  • The thing is - I don't have direct access to it, validation is handled internally through @Valid annotation on entity parameters in controllers' methods. That's one of the reasons why I decided to use custom constraints.
    – Czyzby
    Apr 24, 2015 at 8:46
  • You can add BindingResults as a parameter in your controller's method and check there.
    – StanislavL
    Apr 24, 2015 at 8:55
  • I see, that makes sense. I'll check it out later.
    – Czyzby
    Apr 24, 2015 at 8:58

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.