【问题标题】:Javax Validation Size annotation does not behave correctlyJavax 验证大小注释行为不正确
【发布时间】:2014-12-08 17:24:00
【问题描述】:

所以我有一个像这样的简单类:

import javax.validation.constraints.Size;

public class Temail {

    @Size(min = 0, max = 10)
    private String json;

    public Temail(String json) {
        Validate.notEmpty(json, "json can't be empty");
        setJson(json);
    }

    public void setJson(String json) {
        this.json = json;
    }

    public String getJson() {
        return json;
    }

}

我期待的是,如果我运行new Temail("1234123123123");,我希望它会抛出异常,但它不会。我查看了约定,它确实符合正确的约定。那么这里有什么问题呢?

【问题讨论】:

  • 能否请您附上您的进口声明。有很多不同的验证器,您可能会混合使用它们。
  • 你在用这个@size吗?
  • @dramzy 是的,我正在使用那个

标签: java validation annotations


【解决方案1】:

似乎不应该在约束无效时抛出异常。相反,您使用验证器实例根据您定义的约束来验证字段。所以,是这样的:

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

Temail t = new Temail("123456789012345");

Set<ConstraintViolation<Temail>> constraintViolations = validator.validateProperty(t, "json");

查看更多示例和解释here

【讨论】:

  • 我想这很好,但是如果我们有 10 个字段呢?有没有自动验证的方法?
  • 改为验证对象:validator.validate(t)
猜你喜欢
  • 1970-01-01
  • 2014-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-12
  • 1970-01-01
相关资源
最近更新 更多