簡體   English   中英

使用 javax.validation 進行自定義驗證

[英]Custom validation with javax.validation

我正在嘗試制作自定義 java 驗證注釋並返回給我

請求處理失敗; 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 ConstraintValidationimplements ConstraintValidator<CustomConstraint , List<ElementOfTheList>> {

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

並在 rest object model

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

改變

@SupportedValidationTarget(ValidationTarget.PARAMETERS)

@SupportedValidationTarget(ValidationTarget.ANNOTATED_ELEMENT)

因為您要驗證和元素(這里是列表列表)而不是方法或構造函數的參數

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM