2

can you tell me how to create custom constraint validator which will work for single field and collection as well?

For instance, I have an object Foo which contains the enum of status

public class Foo {
    Status status;
}

Status can be of type active or disabled. I want to ensure when I use my annotation constraint for some field of type Foo or Collection, constraint check if field/fields have set the status to the required value.

samples:

@StatusCheck(Status.ACTIVE)
public Foo foo;

or

@StatusCheck(Status.ACTIVE)
public List<Foo> foo;

Is possible to do that with a single validator? Or should I make two? Thanks in advice.

bugfreerammohan
  • 1,471
  • 1
  • 7
  • 22
Denis Stephanov
  • 4,563
  • 24
  • 78
  • 174

2 Answers2

3

I solve it using multiple validator classes defined in annotations like this:

@Documented
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = { StatusCheckValidator.class, StatusCheckValidatorList.class })
public @interface StatusCheck {

    String message() default "foo.message";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
    Status value();
}

If you know better way how to do that feel free to add your answer :)

Denis Stephanov
  • 4,563
  • 24
  • 78
  • 174
2

Yes, you can use the same validator for Foo and List<Foo>.

For that you will need to upgrade to Hibernate Validator 6.0.x and Bean Validation API 2.0.1. Then you can validate the list elements like this:

public List<@StatusCheck(Status.ACTIVE) Foo> foos;

See also this answer for a similar problem.

You also need to enhance the definition of your @StatusCheck annotation by the target ElementType.TYPE_PARAMETER, so that it will be allowed to put that annotation on a generic type parameter between the < >:

@Target(ElementType.FIELD, ElementType.TYPE_PARAMETER)
....
public @interface StatusCheck {
     ....
}
Thomas Fritsch
  • 9,639
  • 33
  • 37
  • 49
  • Thanks for answer. I checked our version of hibernate validator and it is 5.3.x. It's large project and I can't upgrade dependency right now. Is possible to do that with our version? – Denis Stephanov Aug 23 '18 at 09:43
  • @DenisStephanov No, it is not possible. You need the newer Hibernate Validator, or else the validating annotations within `< >` will be ignored. – Thomas Fritsch Aug 23 '18 at 10:46