英文:
Custom validation with javax.validation
问题
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'.
@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 ConstraintValidation implements 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;
英文:
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;
答案1
得分: 4
将以下部分进行翻译:
将
@SupportedValidationTarget(ValidationTarget.PARAMETERS)
更改为
@SupportedValidationTarget(ValidationTarget.ANNOTATED_ELEMENT)
因为您想要验证一个元素(这里是 List
英文:
change
@SupportedValidationTarget(ValidationTarget.PARAMETERS)
to
@SupportedValidationTarget(ValidationTarget.ANNOTATED_ELEMENT)
since you want to validate and element (here is List<ElementOfTheList> list)
and not the parameters of a method or a constructor
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论