javaspringvalidation

Custom validation with javax.validation


I'm trying to make a custom java validation annotation and returns me

Request processing failed; nested exception is javax.validation.ConstraintDeclarationException: HV000144: Cross parameter constraint com.my.company.CustomConstraint is illegally placed on field 'private java.util.List com.my.company.ElementOfTheList'."

the code is really naive

@Documented
@Retention(RUNTIME)
@Target({ FIELD, METHOD})
@Constraint(validatedBy = ConstraintValidation.class)
public @interface CustomConstraint {

    String message() default "this is the default message";

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

    Class<? extends Payload>[] payload() default {};
}
@SupportedValidationTarget(ValidationTarget.PARAMETERS)
public class ConstraintValidationimplements ConstraintValidator<CustomConstraint , List<ElementOfTheList>> {

    public boolean isValid(List<ElementOfTheList> value, ConstraintValidatorContext context) {
        System.out.println("only a sysout to test");
        return true;
    }
}

And in the rest object model

  @JsonProperty("ElementOfTheList")
  @Valid
  @NotNull(message ="not null message")
  @NotEmpty(message = "not empty message")
  @CustomConstraint 
  private List<ElementOfTheList> list = null;

Solution

  • change

    @SupportedValidationTarget(ValidationTarget.PARAMETERS)
    

    to

    @SupportedValidationTarget(ValidationTarget.ANNOTATED_ELEMENT)
    

    since you want to validate an element (here is List<ElementOfTheList> list) and not the parameters of a method or a constructor