java:validatorinprimefaces
Differences
This shows you the differences between two versions of the page.
| Both sides previous revisionPrevious revisionNext revision | Previous revision | ||
| java:validatorinprimefaces [2012/08/25 22:07] – rlunaro | java:validatorinprimefaces [2022/12/02 21:02] (current) – external edit 127.0.0.1 | ||
|---|---|---|---|
| Line 1: | Line 1: | ||
| + | ====== Validator example in primefaces ====== | ||
| + | |||
| + | Here is the example of a validator in primefaces. The example is based in the following use case: suppose we have a box calle " | ||
| + | |||
| + | This example is run with primefaces in the presentation layer. | ||
| + | |||
| + | <code xhtml> | ||
| + | < | ||
| + | value="# | ||
| + | required=" | ||
| + | requiredMessage="# | ||
| + | validator="# | ||
| + | < | ||
| + | |||
| + | </ | ||
| + | |||
| + | The '' | ||
| + | |||
| + | The backing bean has to have a method called '' | ||
| + | |||
| + | <code java> | ||
| + | |||
| + | 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( " | ||
| + | throw new ValidatorException( fma.getLastMessage() ); | ||
| + | } // username.contains | ||
| + | } | ||
| + | else | ||
| + | { | ||
| + | // if exists in the database, throw exception | ||
| + | fma.addErrorMessage( " | ||
| + | throw new ValidatorException( fma.getLastMessage() ); | ||
| + | } | ||
| + | |||
| + | } // isUsernameValid | ||
| + | |||
| + | </ | ||
| + | |||
| + | |||
| + | The '' | ||
| + | |||
| + | ~~DISQUS~~ | ||
