亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

JSR 303驗證,如果一個字段等于“ something”,則這些其他字段不應為null

JSR 303驗證,如果一個字段等于“ something”,則這些其他字段不應為null

Helenr 2019-12-13 09:31:57
我正在使用JSR-303做一些自定義驗證javax.validation。我有一個領域。而且,如果在此字段中輸入了某個值,則我希望不包含其他一些字段null。我正在嘗試解決這個問題。不確定我該如何稱呼以幫助找到解釋。任何幫助,將不勝感激。我對此很陌生。目前,我正在考慮自定義約束。但是我不確定如何從批注中測試相關字段的值?;旧衔也淮_定如何從注釋訪問面板對象。public class StatusValidator implements ConstraintValidator<NotNull, String> {    @Override    public void initialize(NotNull constraintAnnotation) {}    @Override    public boolean isValid(String value, ConstraintValidatorContext context) {        if ("Canceled".equals(panel.status.getValue())) {            if (value != null) {                return true;            }        } else {            return false;        }    }}這panel.status.getValue();給我帶來麻煩..不確定如何完成此任務。
查看完整描述

3 回答

?
波斯汪

TA貢獻1811條經驗 獲得超4個贊

在這種情況下,我建議編寫自定義驗證器,該驗證器將在類級別進行驗證(以允許我們訪問對象的字段),只有在另一個字段具有特定值時才需要一個字段。請注意,您應該編寫通用驗證器,該驗證器將獲取2個字段名稱,并且僅使用這2個字段。要要求多個字段,您應該為每個字段添加此驗證器。


使用以下代碼作為想法(我尚未對其進行測試)。


驗證器界面


/**

 * Validates that field {@code dependFieldName} is not null if

 * field {@code fieldName} has value {@code fieldValue}.

 **/

@Target({TYPE, ANNOTATION_TYPE})

@Retention(RUNTIME)

@Constraint(validatedBy = NotNullIfAnotherFieldHasValueValidator.class)

@Documented

public @interface NotNullIfAnotherFieldHasValue {


    String fieldName();

    String fieldValue();

    String dependFieldName();


    String message() default "{NotNullIfAnotherFieldHasValue.message}";

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

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


    @Target({TYPE, ANNOTATION_TYPE})

    @Retention(RUNTIME)

    @Documented

    @interface List {

        NotNullIfAnotherFieldHasValue[] value();

    }


}

驗證器實施


/**

 * Implementation of {@link NotNullIfAnotherFieldHasValue} validator.

 **/

public class NotNullIfAnotherFieldHasValueValidator

    implements ConstraintValidator<NotNullIfAnotherFieldHasValue, Object> {


    private String fieldName;

    private String expectedFieldValue;

    private String dependFieldName;


    @Override

    public void initialize(NotNullIfAnotherFieldHasValue annotation) {

        fieldName          = annotation.fieldName();

        expectedFieldValue = annotation.fieldValue();

        dependFieldName    = annotation.dependFieldName();

    }


    @Override

    public boolean isValid(Object value, ConstraintValidatorContext ctx) {


        if (value == null) {

            return true;

        }


        try {

            String fieldValue       = BeanUtils.getProperty(value, fieldName);

            String dependFieldValue = BeanUtils.getProperty(value, dependFieldName);


            if (expectedFieldValue.equals(fieldValue) && dependFieldValue == null) {

                ctx.disableDefaultConstraintViolation();

                ctx.buildConstraintViolationWithTemplate(ctx.getDefaultConstraintMessageTemplate())

                    .addNode(dependFieldName)

                    .addConstraintViolation();

                    return false;

            }


        } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) {

            throw new RuntimeException(ex);

        }


        return true;

    }


}

驗證器用法示例


@NotNullIfAnotherFieldHasValue.List({

    @NotNullIfAnotherFieldHasValue(

        fieldName = "status",

        fieldValue = "Canceled",

        dependFieldName = "fieldOne"),

    @NotNullIfAnotherFieldHasValue(

        fieldName = "status",

        fieldValue = "Canceled",

        dependFieldName = "fieldTwo")

})

public class SampleBean {

    private String status;

    private String fieldOne;

    private String fieldTwo;


    // getters and setters omitted

}

注意,驗證器實現使用庫中的BeanUtils類,commons-beanutils但您也可以使用BeanWrapperImplSpring Framework中的類。


查看完整回答
反對 回復 2019-12-13
?
森林海

TA貢獻2011條經驗 獲得超2個贊

定義必須驗證為true的方法并將@AssertTrue注釋放在其頂部:


  @AssertTrue

  private boolean isOk() {

    return someField != something || otherField != null;

  }

該方法必須以“ is”開頭。


查看完整回答
反對 回復 2019-12-13
  • 3 回答
  • 0 關注
  • 677 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號