Wednesday, January 28, 2009

Creating Your Own Validators in Struts

Even though the Validators provided by the framework cover many of the validation rules that Web applications require, there are special needs that will require you to create your own rules. Fortunately, the Validator framework is easily extensible and the effort to do so is minimal.

To create your own validator, just create a Java class that implements your special validation rule. For example, suppose you needed a rule to validate that a user was the legal drinking age; this might be necessary to purchase alcoholic beverages online. You could possibly use one of the existing validation rules, but it would be more obvious to create a rule to validate that the user meets the required drinking age. The Java class might look something like the one in Example:

import java.io.Serializable;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.validator.Field;
import org.apache.commons.validator.GenericValidator;
import org.apache.commons.validator.ValidatorAction;
import org.apache.commons.validator.ValidatorUtil;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.util.StrutsValidatorUtil;

public class NewValidator implements Serializable{

public static boolean validateDrinkingAge( Object bean,
ValidatorAction va,
Field field,
ActionErrors errors, HttpServletRequest request) {

String value = null;
if (isString(bean)) {
value = (String) bean;
} else {
value =
ValidatorUtil.getValueAsString(bean, field.getProperty());
}
String sMin = field.getVarValue("drinkingAge");

if (!GenericValidator.isBlankOrNull(value)) {
try {
int iValue = Integer.parseInt(value);
int drinkingAge = Integer.parseInt(sMin);

if ( iValue < drinkingAge ){
errors.add(field.getKey(),
StrutsValidatorUtil.getActionError(request, va, field));
return false;
}
} catch (Exception e) {
errors.add(field.getKey(),
StrutsValidatorUtil.getActionError(request, va, field));
return false;
}
}
return true;
}

private static boolean isString(Object o) {
if (o == null) {
return (true);
}
return (String.class.isInstance(o));
}


After you create the new Validator, you simply add it to
the list of existing Validators in the validation-rules.xml
file. Once that's done, you can use the new Validator just
like it was one of the "basic validators."



No comments: