JSF Tip #7 - The RequiredValidator

Say you want to make sure that a value is required.

        
    <html xmlns:h="http://java.sun.com/jsf/html"  xmlns:f="http://java.sun.com/jsf/core">
        <h:inputText value="#{user.firstName}">
            <f:validateRequired/>
        </h:inputText>
    </html>
        

If you want to disable the RequiredValidator on a page you 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:validateRequired disabled="true" />
        </h:inputText>
    </html>
        

If you keep an instance of a RequiredValidator around in your managed bean you can also use binding to bind that particular instance of the RequiredValidator 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:validateRequired binding="#{settings.requiredValidator}" />
        </h:inputText>
    </html>
        

And a managed bean that has a method similar to the one below:

    
    public RequiredValidator getRequiredValidator() {
        return requiredValidator;
    }
        

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:validateRequired binding="#{settings.firstNameValidator}" for="myinput"/>
        </h:inputText>
    </html>
        

Posted September 7, 2012

Up