AdSense

網頁

2018/8/10

Java Bean Validation Constraints @Digits

本篇介紹Java Bean Validation Constraints 的 @Digits的用法。

@Digits可用來指定Java Bean屬性值的位數長度,應填的屬性為integerfraction例如@Digits(integer = 3, fraction = 0)表示屬性值的整數位數長度必須為3,小數位數為0。如果屬性值不符指定長度則違反限制。

使用前要匯入Java Validation API的jar,請參考Java 使用自訂的Java Bean Validation來驗證Bean屬性範例

Customer.java

public class Customer {
  
  private String custId;
  
  @Digits(integer = 3, fraction = 0) // 整數位數3,小數位數0
  private int int1;
  
  @Digits(integer = 3, fraction = 0)
  private String str1; // 數字為字串也OK
  
  @Digits(integer = 1, fraction = 3) // 整數位數1,小數位數0
  private double dou1;
  
  // getter and setter ommitted
}

測試

public class Main {

  public static void main(String[] args) {

    ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
    Validator validator = vf.getValidator();

    Customer customer = new Customer();
    customer.setInt1(1000);
    customer.setStr1("1000");
    customer.setDou1(1.9999);

    validate(validator, customer);

    vf.close();
    
  }

  private static void validate(Validator validator, Customer customer) {
    Set<ConstraintViolation<Customer>> violations = validator.validate(customer);
    if (violations.isEmpty()) {
      System.out.println("pass");
    } else {
      for (ConstraintViolation violation : violations) {
        System.out.println(
            "violation field:" + violation.getPropertyPath()
            + "=" + violation.getInvalidValue()
            + ", message:" + violation.getMessage());
      }
      throw new ConstraintViolationException(violations);
    }
  }
}

結果如下

violation field:str1=1000, message:numeric value out of bounds (<3 digits>.<0 digits> expected)
violation field:dou1=1.9999, message:numeric value out of bounds (<1 digits>.<3 digits> expected)
violation field:int1=1000, message:numeric value out of bounds (<3 digits>.<0 digits> expected)
Exception in thread "main" javax.validation.ConstraintViolationException: str1: numeric value out of bounds (<3 digits>.<0 digits> expected), dou1: numeric value out of bounds (<1 digits>.<3 digits> expected), int1: numeric value out of bounds (<3 digits>.<0 digits> expected)
 at idv.matt.main.Main.validate(Main.java:62)
 at idv.matt.main.Main.main(Main.java:39)

參考:

沒有留言:

AdSense