ValidationUtils 提供一些基本的驗證 method。
public class PersonValidator implements Validator {
private Validator addressValidator;
private PersonValidator(Validator addressValidator) {
if (addressValidator == null) {
throw new IllegalArgumentException(
"The supplied [Validator] is required and must not be null.");
}
if (!addressValidator.supports(Address.class)) {
throw new IllegalArgumentException(
"The supplied [Validator] must support the validation of [Address] instances.");
}
this.addressValidator = addressValidator;
}
@Override
public boolean supports(Class<?> clazz) {
// just Person
return Person.class.equals(clazz);
// Person and subclass
// return Person.class.isAssignableFrom(clazz);
}
@Override
public void validate(Object obj, Errors e) {
ValidationUtils.rejectIfEmpty(e, "name", "The name is required");
Person p = (Person) obj;
if (p.getAge() < 0) {
e.rejectValue("age", "Too young");
}
else if (p.getAge() > 110) {
e.rejectValue("age", "Too old");
}
try {
e.pushNestedPath("address");
ValidationUtils.invokeValidator(this.addressValidator,
p.getAddress(), e);
}
finally {
e.popNestedPath();
}
}
public static void main(String[] args) {
Person target = new Person();
DataBinder binder = new DataBinder(target);
binder.setValidator(new PersonValidator(new AddressValidator()));
// bind to the target object
binder.bind((propertyValues);
// validate the target object
binder.validate();
// get BindingResult that includes any validation errors
BindingResult results = binder.getBindingResult();
System.out.println(results);
}
}
沒有留言:
張貼留言