Question

We are migrating from JSF 1.2 to JSF2. We are facing issue in validation.We are using apache myfaces 2 and rich faces 4.3 Below is the xhtml code :

<h:form id="form">      
            <ui:include src="panel1.xhtml"/>

                <h:commandButton id="btn1" value="Submit" action="#{bean.submit}"/>

</h:form>

panel1.xhtml contains a custom component as below :

  <h:panelGrid columns="2">

               <h:outputText value="Enter Phone"/>                                 
               <h:inputText id="compId" value="#{map['Phone']}" size="12" maxlength="20"  required="true" 
               validator="#{validator.validatePhone}"/>

           <!-- other components omitted  -->
 </h:panelGrid>

 public void validatePhone(FacesContext arg0, UIComponent arg1, Object obj)
            throws ValidatorException {

        String phoneVal = (String) obj;

        if(phoneVal .length() <5){
            //rest of the code is omitted 
        }

}

The issue is , when phone value is not entered (kept empty) , and the form is submitted , following are the observations.

JSF 2 : validator.validatePhone is called with Object obj value (in validatePhone method)as null

JSF 1.2 : required = "true" attribute takes into effect first and validator.validatePhone is not called at all (if there is no value in Phone field) and validation errors are displayed.

Question is :

1)Why validator.validatePhone is called for JSF 2 even though there is no value in Phone field ? 2)Why is there a change in behaviour in JSF 1.2 and JSF 2 for above case ?

Was it helpful?

Solution

The reason for the inconsistency is that in JSF2, null values do not fail validation by default. From the Javadocs:

For a validator to be fully compliant with Version 2 and later of the specification, it must not fail validation on null or empty values unless it is specifically intended to address null or empty values

To support the validation behaviour from JSF1.2, use the javax.faces.VALIDATE_EMPTY_FIELDS context parameter:

<context-param>
    <param-name>javax.faces.VALIDATE_EMPTY_FIELDS</param-name>
    <param-value>false</param-value>
</context-param>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top