JSF standard validator tags allow the binding
attribute (this is also true for listener and converter tags). This means that developers can bind validator implementations to backing bean properties. The main advantages of using the binding facility are:
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.
To successfully accomplish a binding task, you can follow three simple steps (these steps are true for converter, listener, and validator tags):
binding
attribute of the validator (listener, converter) tag.As per the example, let's bind the standard f:validateLongRange
validator to a backing bean property. The idea is to let the backing bean set the values for the minimum
and maximum
attributes. First, you have to register the validator onto the component by nesting the f:validateLongRange
tag within the component tag. Then, you have to reference the property with the binding
attribute of the f:validateLongRange
tag.
<h:form id="IpForm"> <h:outputText value="Insert your age:"/><br /> <h:inputText id="ageID" required="true" value="#{userBean.userAge}"> <f:validateLongRange binding="#{userBean.longAge}"/> </h:inputText> <h:message showSummary="true" showDetail="false" for="ageID" style="color: red; text-decoration:overline"/> <br /> <h:commandButton id="submit" action="response?faces-redirect=true" value="Submit"/> </h:form>
The longAge
property is defined in the following managed bean:
package users; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.validator.LongRangeValidator; @ManagedBean @SessionScoped public class UserBean { private int userAge; private LongRangeValidator longAge; public int getUserAge(){ return this.userAge; } public void setUserAge(int userAge){ this.userAge=userAge; } public LongRangeValidator getLongAge(){ return this.longAge; } public void setLongAge(LongRangeValidator longAge){ longAge.setMinimum(18); longAge.setMaximum(90); this.longAge=longAge; } }
In our example, the backing bean sets the minimum
and maximum
values within the f:validateLongRange
tag, which means that the user's input will be constrained by these boundaries. This time the number's range is indicated without using specific attributes in f:validateLongRange
tag. Instead of this, we use the binding
attribute to reference the longAge
property, which is a LongRangeValidator
instance, offering us access to this class's methods.