Listing 9-2.Validator Implementation for Address Objects
package com.apress.expertspringmvc.validation;
import org.springframework.validation.Validator;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
public class EasyAddressValidator implements Validator {
public boolean supports(Class clazz) {
Address.class.isAssignableFrom(clazz);
}
public void validate(Object target, Errors errors) {
ValidationUtils.rejectIfEmtpy(errors, "location", "addressLocationEmpty");
}
}
This Validatorrejects the location property on the Addressclass if the property value is
empty (nullor a zero-length string). addressLocationEmptyis the error code that’s looked up
through an org.springframework.context.MessageSourceinstance; by default this is the
ApplicationContext.
Let’s extend the Addressdomain class Validator. See Listing 9-3.
Listing 9-3.More Elaborate Validator for Address Objects
package com.apress.expertspringmvc.validation;
import org.springframework.validation.Validator;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
public class AddressValidator implements Validator {
public boolean supports(Class clazz) {
return Address.class.isAssignableFrom(clazz);
}
public void validate(Object target, Errors errors) {
ValidationUtils.rejectIfEmpty(errors, "city", "cityEmpty");
ValidationUtils.rejectIfEmpty(errors, "location", "locationEmpty");
ValidationUtils.rejectIfEmpty(errors, "postalCode", "postalCodeEmpty");
ValidationUtils.rejectIfEmpty(errors, "country", "countryIsEmpty");
}
}
266 CHAPTER 9 ■VALIDATION