简体   繁体   English

Java Bean条件验证

[英]Java Bean Conditional Validation

I have a class with two attributes. 我有两个属性的类。 I want to use Java Bean Validation but ran with one problem on how to approach? 我想使用Java Bean验证,但是遇到了一个关于如何处理的问题?

class ProductRequest {

   private String quantityType;
   private double quantityValue;

   //getters and setters
}

I want to use Java Bean Validation based on below condition. 我想基于以下条件使用Java Bean验证。 If "quantityType" is equals to "foo", limit "quantityValue" to maximum size of 5 else "quantityType" is equals to "bar", limit "quantityValue" to maximum size of 3. 如果“ quantityType”等于“ foo”,则将“ quantityValue”限制为最大大小5,否则“ quantityType”等于“ bar”,将“ quantityValue”限制为最大大小3。

What will be the best way to approach in this scenario? 在这种情况下最好的方法是什么?

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;
}

EDIT: 编辑:

Addressing question from comment. 通过评论解决问题。 You can try using two methods at once: 您可以尝试同时使用两种方法:

@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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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