当您说这时this validation never takes place
,您指的是 myField 为空或已填充(或两者之一)的情况吗?
由于我也在我的一个项目中使用了验证器,所以我运行了一个小测试,当 myField 为空时,它没有经过验证。当它不为空时,它是。我正在使用以下版本:
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.0.1.Final</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.el</artifactId>
<version>2.2.4</version>
</dependency>
这是测试代码:
public class MyClass {
public MyClass() {
}
public MyClass(String myField) {
this.myField = myField;
}
@Pattern(regexp="\\d+\\D+")
private String myField;
}
public class ParentClass {
@Valid
private MyClass myClass;
public ParentClass() {
}
public ParentClass(MyClass myClass) {
this.myClass = myClass;
}
}
public class ValidatorTest {
javax.validation.Validator v;
@Before
public void setup() {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
v = factory.getValidator();
}
@Test
public void testValidations() {
Assert.assertEquals(0, v.validate(new ParentClass()).size()); // Null reference
Assert.assertEquals(0, v.validate(new ParentClass(new MyClass())).size()); // Valid reference, null field
Assert.assertEquals(1, v.validate(new ParentClass(new MyClass("I fail"))).size());
Assert.assertEquals(0, v.validate(new ParentClass(new MyClass("1 pass"))).size());
}
}
我希望这有帮助。看来(对我而言)所展示的行为是正确的。