Another validator available starting with JSF 2.0 is f:validateRegex
. This validator uses the pattern
attribute to validate the wrapping component. The value of pattern
is provided as a Java regular expression. In this recipe, you will see how to use this validator to validate an e-mail address against the proper regular expression.
We developed this recipe with NetBeans 6.8, JSF 2.0, and GlassFish v3. The JSF 2.0 classes were obtained from the NetBeans JSF 2.0 bundled library.
The following code snippet validates the value provided into a UIInput
component as an e-mail address value:
… <h:form> <h:outputText value="E-mail:"/> <h:inputText value="#{emailBean.email}" validatorMessage="You must provide an e-mail of type [email protected]!"> <f:validateRegex pattern= "[a-zA-Z0-9_]*[@]{1}[a-zA-Z0-9_]*[.]{1}[a-zA-Z]{2,3}" /> </h:inputText> <h:commandButton value="Submit" action= "index?faces-redirect=true"/> </h:form> …
The f:validateRegex
works exactly as expected—the entire pattern is matched against the provided String
value of the component. If it matches, it's valid, otherwise a validation error message is returned.
The code bundled with this book contains a complete example of this recipe. The project can be opened with NetBeans 6.8 and it is named: validateRequired_and_validateRegex_tags
.
More details about the f:validateReqex
tag specification can be found at https://javaserverfaces.dev.java.net/nonav/docs/2.0/pdldocs/facelets/f/validateRegex.html.