这是自定义验证器,具有countryCode的getter / setter
public void validate(Object object) throws ValidationException {
String fieldName = getFieldName();
Object zipObj = this.getFieldValue(fieldName, object);
String country = getCountryCode();
String zipCode = (String) zipObj;
if (zipCode == null || ("".equals(zipCode))) {
return;
}
boolean valid = false;
try {
if ((Country.DEFAULT).equalsIgnoreCase(country)) {
valid = Pattern.matches(US_ZIP_FORMAT, zipCode);
int testZip = Integer.parseInt(zipCode.substring(0, 5));
if (testZip == 0) {
valid = false;
}
} else if ((Country.CANADA).equalsIgnoreCase(country)) {
valid = Pattern.matches(CANADA_ZIP_FORMAT, zipCode);
} else {
valid = Pattern.matches(OTHER_ZIP_FORMAT, zipCode);
}
} catch (Exception e) {
logger.error("Cannot validate zip code (" + zipCode + ") for country ("
+ country + ").");
valid = false;
}
if (!valid) {
addFieldError(fieldName, object);
}
}
如何将国家/地区代码传递回自定义验证程序。这是我的ActionClass-validation.xml
<validators>
<field name="address.zip">
<field-validator type="zipValidator">
<param name="countryCode">${address.country}</param>
<message key="errors.zip.invalid" />
</field-validator>
</field>
</validators>
地址对象有zip和countryCode。我想根据国家/地区验证zip。当我调试上面的代码时,countryCode的值为${address.country}
。
如何获取国家/地区属性值?
答案 0 :(得分:0)
您需要从ValidatorSupport
扩展自定义验证程序。然后在实现代码中,如果它是OGNL表达式,您可以使用parse
方法获取参数的值。
String country = (String) parse(this.countryCode, String.class);