0

I'm trying to have one validator use multiple constraints withtout success. The @Constraint annotations take an array as input; and as described in this post, it should be possible: Multiple validation options in Annotation.

When I try to validate a Resource, I get the following error

HV000150: The constraint NirValidator defines multiple validators for the type NirResource: NirCalculCleConstraint, NirBrutLongueurConstraint. Only one is allowed

Here is my interface:


@Documented
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = {NirCalculCleConstraint.class, NirBrutLongueurConstraint.class})
public @interface NirValidator {

    String message() default "";

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

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

and those 2 constraints classes:

public class NirBrutLongueurConstraint implements ConstraintValidator<NirValidator, NirResource> {
    @Override
    public boolean isValid(NirResource value, ConstraintValidatorContext constraintValidatorContext) {
        return value == null || value.toString().length() == LONGUEUR_MIN_NIR || value.toString().length() == LONGUEUR_MAX_NIR;
    }
}

public class NirCalculCleConstraint implements ConstraintValidator<NirValidator, NirResource> {
 
    private int calculerCle(NirResource value) {
        return (int) (CONSTANTE_CALCUL_CLE_NIR - ((Long.parseLong(value.toString(false))) % CONSTANTE_CALCUL_CLE_NIR));
    }

    @Override
    public boolean isValid(NirResource value, ConstraintValidatorContext constraintValidatorContext) {
        return Integer.parseInt(value.getCleNir()) != calculerCle(value);
    }
}

All I could find online concerning thie error code is this link but it's not relevant in my situation as the lib mentionned is not on my classpath.

  • You can have only multiple validators for different types not for the same type. That is also the case in the question you linked. – M. Deinum Feb 21 '23 at 15:20
  • Damn, thank you !! I was banging my head on this one. It makes a bit of sense I guess, but I feel like the error message is not clear; or maybe I just did not understand it correctly. – Bancarel Valentin Feb 21 '23 at 15:33
  • Well the message is clear (at least IMHO). **HV000150: The constraint NirValidator defines multiple validators for the type NirResource** states that the validator contains more then 1 validator for a specific type. – M. Deinum Feb 21 '23 at 15:34
  • Yes it does now i read it knowing what it mean; I guess my brain was just not working when seeing it first time – Bancarel Valentin Feb 23 '23 at 09:37

0 Answers0