There are three clear trends towards building web-pages these days: PHP, ASP, and JSP / JSF / Struts.
This post addresses the problem of writing custom data validators for web forms.
Validators are introduced in JSF pages by the “validator” tag, a custom input field looking like:
The name of the validator is given by the validatorId.
The mapping between the validatorId and the class handling the validation is done through the faces-config.xml.
<?xml version=’1.0′ encoding=’UTF-8′?>
<faces-config version=”1.2″
xmlns=”http://java.sun.com/xml/ns/javaee”
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
xsi:schemaLocation=”http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd”>
<managed-bean>
…
</managed-bean>
<navigation-rule>
<from-view-id> … </from-view-id>
<navigation-case>
<from-outcome>…</from-outcome>
<to-view-id>…</to-view-id>
</navigation-case>
</navigation-rule>
<validator>
<validator-id>NameValidator</validator-id>
<validator-class>NameValidator</validator-class>
</validator>
</faces-config>
The name validator is backed up by some Java code, that handles the corresponding validation. Basically a custom field validator implements the marker interface javax.faces.validator.Validator, having a single method called validate. The data is passed to our validating class through the mediation of the “value” object, which has to be cast to the type we are expecting it to be. To offer greater flexibility I created an Abstract Class which handles all the JSF’s API calls, which is latter implemented by a concrete class.
-
import javax.faces.application.FacesMessage;
-
import javax.faces.component.UIComponent;
-
import javax.faces.context.FacesContext;
-
import javax.faces.validator.Validator;
-
import javax.faces.validator.ValidatorException;
-
-
public abstract class AbstractValidator implements Validator{
-
-
public abstract boolean validValue(String text);
-
public abstract String getErrorMessage();
-
-
public void validate(FacesContext context, UIComponent component,
-
Object value) {
-
-
if (value == null) return;
-
-
String text = value.toString();
-
-
if (!validValue(text)) {
-
FacesMessage message = new FacesMessage(
-
FacesMessage.SEVERITY_ERROR,
-
getErrorMessage(), null);
-
throw new ValidatorException(message);
-
}
-
}
-
}
The concrete class adapts our abstract validator to our needs :
-
public class NameValidator extends AbstractValidator {
-
-
private char prohibited[] = {'/', '.'};
-
private static String ERROR_MESSAGE = "Invalid name format.";
-
-
@Override
-
public String getErrorMessage(){
-
return ERROR_MESSAGE;
-
}
-
-
@Override
-
public boolean validValue(String text) {
-
if (text.length()==0) {
-
return false;
-
}
-
for (int i = 0; i < prohibited.length; i++) {
-
if (text.indexOf(prohibited[i]) != -1) {
-
return false;
-
}
-
}
-
return true;
-
}
-
}