1

我正在运行这段代码。如果我将验证注释添加到 1 个字段,则会正确提取违规。但是,如果我在超过 1 个字段上添加注释,则根本不会发现任何违规行为。

public class Address implements Serializable {

    private static final long serialVersionUID = 225035939665473333L;

    @NotNull
    @NotEmpty
    @Size(min = 4, max = 50, message="test")
    private String Name;

    @NotNull
    @NotEmpty
    private String AddressLine1;

    private String AddressLine2;
    private String PostalCode;
    private String Province;

    @NotNull
    @NotEmpty
    private String Country;

    //getter and setters below this line
}

我正在运行此代码:

ValidatorFactory factory = Validation.byDefaultProvider().configure().buildValidatorFactory();
Validator validator = factory.getValidator();
Address a = new Address();
a.setName("a");

Set<ConstraintViolation<Address>> violations = validator.validate(a);

Window.alert(String.valueOf(violations.size()));
for(ConstraintViolation<Address> violation : violations){
    Window.alert(violation.getMessage());
}

这将拾取零错误,即使它应该拾取 3 个错误。AddressLine1, Country 不应为空。名字太短。如果我将类更改为下面的代码,它将发现名称太短并显示错误消息“test”。

public class Address implements Serializable {

    private static final long serialVersionUID = 225035939665473333L;

    @NotNull
    @NotEmpty
    @Size(min = 4, max = 50, message="test")
    private String Name;

    private String AddressLine1;

    private String AddressLine2;
    private String PostalCode;
    private String Province;

    private String Country;

    //getter and setters below this line
}
4

0 回答 0