我有以下模型类
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
public class Person {
@Max(value = 10, message = "First name should be smaller than 10 characters.")
private String fname;
@Min(value = 5, message = "Last name should have atleast 5 characters.")
private String lname;
private String status;
public Person(String fname, String lname, String status) {
super();
this.fname = fname;
this.lname = lname;
this.status = status;
}
以下是我正在验证 Person 模型类的测试类。
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Set;
import javax.validation.Configuration;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import the.bhushan.models.Person;
public class Test {
public static void main(String[] args) throws FileNotFoundException {
Test test = new Test();
//test.byXML();
test.byAnnotation();
}
private void byAnnotation() {
ValidatorFactory validatorFactory = Validation
.buildDefaultValidatorFactory();
Validator validator = validatorFactory.getValidator();
Person emp1 = new Person("Bhushan", "Patil", "A");
Set<ConstraintViolation<Person>> validationErrors = validator
.validate(emp1);
if (!validationErrors.isEmpty()) {
for (ConstraintViolation<Person> error : validationErrors) {
System.out.println(error.getMessageTemplate() + "::"
+ error.getPropertyPath() + "::" + error.getMessage());
}
}
}}
即使 fname 字段的值只有 7 个字符长,它也会显示以下验证消息。
姓氏至少应包含 5 个字符。::lname::姓氏应至少包含 5 个字符。名字应该小于 10 个字符。::fname::名字应该小于 10 个字符。