Using regular expressions with f:validateRegex

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.

Getting ready

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.

How to do it...

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>
…

How it works...

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.

See also

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset