package validators; import java.util.regex.Pattern; 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 class PincodeValidator implements Validator { public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException { // check whether value is starting with 53 and contains 4 digits after that. if (! Pattern.matches("^53\\d{4}$", value.toString())) throw new ValidatorException( new FacesMessage("Invalid Pincode!",null)); // error, so throw exception } }
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE faces-config PUBLIC "-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.1//EN" "http://java.sun.com/dtd/web-facesconfig_1_1.dtd"> <!-- =========== FULL CONFIGURATION FILE ================================== --> <faces-config> <!-- other entries --> <validator> <description>Validator to validate Pincode </description> <validator-id>pincodevalidator</validator-id> <validator-class>validators.PincodeValidator</validator-class> </validator> </faces-config>
<%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Testing PincodeValidator</title> </head> <body> <h3>Testing Custom Validator</h3> <f:view> <h:form id="form1"> Enter Pincode : <h:inputText id="pincode" required="true" > <f:validator validatorId="pincodevalidator" /> </h:inputText> <h:message id="errmsg" for="pincode" /> <p/> <h:commandButton value="Submit" type="submit" /> </h:form> </f:view> </body> </html>