Here is the example of a validator in primefaces. The example is based in the following use case: suppose we have a box calle “username” that has to be validated to see if the user entered new username exists previously in the database.
This example is run with primefaces in the presentation layer.
<p:inputText id="txtUsername" value="#{profileForm.username}" required="true" requiredMessage="#{msg.get('fieldIsRequired')}" validator="#{profileForm.isUsernameValid}"/> <p:message for="txtUsername"/>
The message
tag wil hold the messages related with the validation errors. You can also use a <p:growl> tag for this.
The backing bean has to have a method called isUsernameValid
to properly validate the username. Here is an example:
import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.validator.ValidatorException; /** * Validates if the new username is available or not */ public void isUsernameValid(FacesContext ctx, UIComponent component, Object value) throws ValidatorException { String newUsername = value.toString(); // if the username hasn't changed, is valid if( newUsername.equals( initialUsername ) ) return; // if the username has changed, but it is // available in the database, is correct if( !usersController.userExists(newUsername) ) { // if it contains an space in the username, // throw exception if( newUsername.contains( " " ) ) { fma.addErrorMessage( "usernameIncorrectFormat" ); throw new ValidatorException( fma.getLastMessage() ); } // username.contains } else { // if exists in the database, throw exception fma.addErrorMessage( "usernameAlreadyExists" ); throw new ValidatorException( fma.getLastMessage() ); } } // isUsernameValid
The fma
object is a helper object that has a method to create a new faces message out of the resources of the application, instead of using a constant literal which will have problems for translating into various languages.
~~DISQUS~~