2

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.)

1
  • Do you mean that BOTH the validators must return true for the value to be valid? Commented Jan 29, 2021 at 16:39

1 Answer 1

7

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> { ... }
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, I checked it and it works for me. The annotations go to the proper class for validation.
ConstraintValidator<A extends Annotation, T>. How are object Phone and Contact of type Annotation?
@AdiV you’re right. The validator definitions were wrong. I updated them.
That does not work for me; I get this error: HV000150: The constraint NirValidator defines multiple validators for the type NirResource: NirCalculCleConstraint, NirBrutLongueurConstraint. Only one is allowed.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.