13.2.3.2. 实施约束验证器
在定义了注释后,您需要创建一个能够使用 @Address
注释验证元素的约束验证器。要做到这一点,实施接口 ConstraintValidator
,如下所示:
示例: 地址验证器
类
package org.jboss.as.quickstarts.bean_validation_custom_constraint; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import org.jboss.as.quickstarts.bean_validation_custom_constraint.PersonAddress; public class AddressValidator implements ConstraintValidator<Address, PersonAddress> { public void initialize(Address constraintAnnotation) { } /** * 1. A null address is handled by the @NotNull constraint on the @Address. * 2. The address should have all the data values specified. * 3. Pin code in the address should be of at least 6 characters. * 4. The country in the address should be of at least 4 characters. */ public boolean isValid(PersonAddress value, ConstraintValidatorContext context) { if (value == null) { return true; } if (value.getCity() == null || value.getCountry() == null || value.getLocality() == null || value.getPinCode() == null || value.getState() == null || value.getStreetAddress() == null) { return false; } if (value.getCity().isEmpty() || value.getCountry().isEmpty() || value.getLocality().isEmpty() || value.getPinCode().isEmpty() || value.getState().isEmpty() || value.getStreetAddress().isEmpty()) { return false; } if (value.getPinCode().length() < 6) { return false; } if (value.getCountry().length() < 4) { return false; } return true; } }