Enforcing a value's presence with f:validateRequired

Starting with JSF 2.0, a new set of validators is available. One of these is the f:validateRequired, which is a validator used to enforce the presence of a value. In practice, its effect is the same as the required attribute set to true on a UIInput component. In this recipe, you will see an example of using this new validator.

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 example will make things clear in a few seconds. We assume a UIInput component used for grabbing an e-mail address from the user. Since we want to enforce the necessity of this e-mail address we can use f:validateRequired, as shown next:

…
<h:form>
<h:outputText value="E-mail:"/>
<h:inputText value="#{emailBean.email}"
validatorMessage="You must provide an e-mail of type
[email protected]!">
<f:validateRequired/>
</h:inputText>
<h:commandButton value="Submit"
action="index?faces-redirect=true"/>
</h:form>
…

How it works...

As we said earlier, it works like the required attribute set it to true on a UIInput component. As per the example, the following code does the same thing, without using the f:validateRequired:

…
<h:form>
<h:outputText value="E-mail:"/>
<h:inputText value="#{emailBean.email}" required="true"
requiredMessage="You must provide an e-mail of type
[email protected]!" />
<h:commandButton value="Submit"
action="index?faces-redirect=true"/>
</h:form>
…

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:validateRequired tag specification can be found at https://javaserverfaces.dev.java.net/nonav/docs/2.0/pdldocs/facelets/f/validateRequired.html

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

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