Java Bean 条件验证

Sus*_*ota 2 java spring javabeans bean-validation

我有一个具有两个属性的类。我想使用 Java Bean 验证,但遇到了一个关于如何处理的问题?

class ProductRequest {

   private String quantityType;
   private double quantityValue;

   //getters and setters
}
Run Code Online (Sandbox Code Playgroud)

我想根据以下条件使用 Java Bean 验证。如果“quantityType”等于“foo”,则将“quantityValue”限制为最大大小为 5,否则“quantityType”等于“bar”,将“quantityValue”限制为最大大小为 3。

在这种情况下,最好的方法是什么?

Kry*_*n G 5

import javax.validation.constraints.AssertTrue;


@AssertTrue
public boolean isBothFieldsValid() {
    if (quantityType.equals("foo")) {
        return quantityValue < 5;
    } else if (quantityType.equals("bar")) {
        return quantityValue < 3;
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

编辑:

从评论中解决问题。您可以尝试同时使用两种方法:

@AssertTrue(message = "quantity should be below 5 for foo")
public boolean isQuantityValidForFoo() {
    if (quantityType.equals("foo")) {
        return quantityValue < 5;
    }
    return true;
}

@AssertTrue(message = "quantity should be below 3 for bar")
public boolean isQuantityValidForBar() {
    if (quantityType.equals("bar")) {
        return quantityValue < 3;
    }
    return true;
}
Run Code Online (Sandbox Code Playgroud)