简体   繁体   中英

javax validation - cross field validation for null check

In the below code, I want to use javax validation to check if either both currency and amount is null or both are not null. The validation should throw an error if either one of those is not null and other is null.

Ex: currency == null && amount == null is true

currency == null && amount == 100 is false

currency == "Dollar" && amount == null is false

currency == "Dollar && amount == 100 is true

public class fee {
  private String currency;

  private Double amount;
}
public class TransactionFee {
  @NotNull
  private String basis;

  @NotNull
  private Double rate;
}

checks only if both are not null

public class TransactionFee {
  @Null
  private String basis;

  @Null
  private Double rate;
}

checks only if both are null

I would like to know if there is any way to implement cross field validation for null check

As @A Le Dref mentioned, you will need to use a class level validator instead of a field level validator.

An example can be found in this stack overflow answer .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM