0

I have a custom validator like this:

@Retention(RetentionPolicy.RUNTIME)
@NotBlank(message = "{state.NotBlank}") // Err...it doesn't work
@Constraint(validatedBy = { State.Validator.class })
public @interface State {
  String message() default "{state.invalid}";

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

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

  @Component
  final class Validator implements ConstraintValidator<State, String> {
    @Override
    public void initialize(final State constraintAnnotation) { }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
      // return true or false based on some rules
    }
  }
}

But there is not way I can make it work annotating State with @NotBlank — since the later doesn't have the ElementType.TYPE in @Target), but annotating the fields themselves with @NotBlank.

The reason I would like to have it in State is because I have to repeat the same constraint to several fields, so if State could be annotated with @NotBlank would be perfect.

Any clues?

x80486
  • 6,627
  • 5
  • 52
  • 111

1 Answers1

0

You cant. You will need to define a new annotation because @NotBlank has the following targets:

@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })

AS you can see you can not apply it to your full interface.

Camilo Sanchez
  • 117
  • 1
  • 7
  • Yeah, I know it doesn't have `ElementType.TYPE`, but I was wondering if there was a work-around for that... – x80486 Jul 27 '18 at 20:27
  • What do you expect it to check? All fields? – Camilo Sanchez Jul 28 '18 at 00:12
  • No, just the ones annotated with `@State`. I was able to change this requirement, but I don't think there is a way to do this in any case, so your answer is valid. – x80486 Jul 28 '18 at 01:10