If you want to validate input against a regular expression then you would use the RegexValidator.
Say you want to make sure only letters are used for a name.
<html xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core"> <h:inputText value="#{user.firstName}"> <f:validateRegex pattern="[a-zA-Z]"/> </h:inputText> </html>
The pattern mentioned above do not have to be a fixed value, you can use an EL expression if you have different requirements for different usage patterns. Note the pattern needs to evaluate to a String.
<html xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core"> <h:inputText value="#{user.firstName}"> <f:validateRegex pattern="#{settings.namePattern}" /> </h:inputText> </html>
If you want to disable the RegexValidator on a page your can mark the validator as disabled as follows:
<html xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core"> <h:inputText value="#{user.firstName}"> <f:validateRegex disabled="true" pattern="[a-zA-Z]" /> </h:inputText> </html>
If you keep an instance of a RegexValidator around in your managed bean you can also use binding to bind that particular instance of the RegexValidator to the tag on the page like so:
<html xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core"> <h:inputText value="#{user.firstName}"> <f:validateRegex binding="#{settings.firstNameValidator}" /> </h:inputText> </html>
And a managed bean that has a method similar to the one below:
public RegexValidator getFirstNameValidator() { return firstNameValidator; }
If you specifically want to attach the validator to a specific component then you can use the 'for' attribute to target it. Note this attribute is really helpful when using composite components. Eg.
<html xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core"> <h:inputText id="myinput" value="#{donation.amount}"> <f:validateRegex binding="#{settings.firstNameValidator}" for="myinput"/> </h:inputText> </html>
Posted September 6, 2012