Monday, November 20, 2006

Plugging your custom validation class into Struts Validator

1. Design your class that has the method that will be invoked when the validator is called.

2. Create a new validator tag in the validator-rules.xml to referecne this class/method

3. In your validation.xml use the new validator tag whereever you want to validate a form field.



Here is a class: The step 1:

public class HMFieldChecks extends FieldChecks {

public static final Pattern VALID_EMAIL_PATTERN =
Pattern.compile("^([a-zA-Z0-9_'\\-\\.\\+]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-\\_\\+]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");

public static boolean validateEmail(Object bean, ValidatorAction va, Field field, ActionMessages errors, HttpServletRequest request) {
String value = null;
if (isString(bean)) {
value = (String) bean;
} else {
value = ValidatorUtils.getValueAsString(bean, field.getProperty());
}

if (StringUtils.isBlank(value) || !isValidEmailAddressFormat(value)) {
errors.add(field.getKey(), Resources.getActionMessage(request, va, field));
return false;
} else {
return true;
}
}


public static boolean isValidEmailAddressFormat(String email) {
return VALID_EMAIL_PATTERN.matcher(email).find();
}

}

This is step 2 ----------------

classname="com.foo.web.util.HMFieldChecks"
method="validateEmail"
methodParams="java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionMessages,
javax.servlet.http.HttpServletRequest"
depends=""
msg="errors.email"/>


The step 3



property="email"
depends="required,email">