Reputation: 5241
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.
Upvotes: 2
Views: 1363
Reputation: 10127
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 {
....
}
Upvotes: 2
Reputation: 5241
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 :)
Upvotes: 3