SyntaxRules
SyntaxRules

Reputation: 2206

Multiple validation options in Annotation

My question is a branch of of this one.

I have a Annotation (say phone annotation) that I want to validate. I can use @phone validator to check if a phone object is valid or not. I want to also be able to place this validator on a contact information object that contains a phone. Is there a way to use multiple validators for one annotation so I can use @phone for my phone object and my contact information object?

Would something like
@Constraint(validatedBy = {PhoneIsValid.class, PhoneIsValid2.class})
work? (The idea being one Validator handles the phone object and the other handles the contact information object.)

Upvotes: 2

Views: 4964

Answers (1)

matthias
matthias

Reputation: 721

It is possible to have multiple validators for the same annotation type. As you mentioned, you have define all of them in the @Constraint annotation.

Annotaion:

@Documented
@Target({ ElementType.ANNOTATION_TYPE, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = { ValidPhonePhoneValidator.class, ValidPhoneContactValidator.class })
public @interface ValidPhone {

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

Validator1:

public class ValidPhonePhoneValidator implements ConstraintValidator<ValidPhone, Phone> { ... }

Validator2:

public class ValidPhoneContactValidator implements ConstraintValidator<ValidPhone, Contact> { ... }

Upvotes: 7

Related Questions