This is the custom validator, has getters/setters for countryCode
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);
}
}
How to pass the country code back to the custom validator. This is my 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>
Address object has zip and countryCode
. I want to validate the zip based on the country. When I debug the above code, countryCode
has the value ${address.country}
.
How can I get the country property value?
You need to extend your custom validator from ValidatorSupport
. Then in the implementation code you can use parse
method to get the value of parameter if it's an OGNL expression.
String country = (String) parse(this.countryCode, String.class);