How to hightlight a field in JSF when validation fails

Highlighting an input field that failed validation (or conversation) is a common UI practice today. This sort of functionality is not available in JSF (nor RichFaces) out of the box (Seam does have it). I got an email from RichFaces 4 workshop attendee from CONFESS_2011 conference asking how to do it and I thought it’s a good idea to make it blog post. It turns out, implementing such functionality is pretty simple. All we need to do is check if a particular field (component) is valid and then render or not render a style for the input field.

Let’s start with the Java bean:

@ManagedBean
@RequestScoped
public class Bean implements Serializable {
 
   private String text; // getter and setter
 
   public boolean isInputValid (){
      FacesContext context = FacesContext.getCurrentInstance();
      UIInput input = (UIInput)context.getViewRoot().findComponent(":form:input");
      return input.isValid();
   }
}

Inside isInputValid, we are searching for a particular component and checking whether it’s valid or not.

JSF page:

<h:head>
<style>
.inputInvalid {
   border: 2px solid red;
}
</style>
</h:head>
<h:body>
   <h:form id="form">
      <h:panelGrid columns="2">
         <h:outputText value="Text:" />
	 <h:panelGroup id="inputGroup">
	    <h:inputText id="input" value="#{bean.text}" 
               styleClass="#{bean.inputValid?'':'inputInvalid'}" 
               required="true" requiredMessage="Value required">
		<a4j:ajax event="blur" render="inputGroup"/>
	    </h:inputText>
	    <h:message for="input" style="padding: 0.5em"/>
	 </h:panelGroup>
      </h:panelGrid>
   </h:form>
</h:body>

Everything important happens here:

styleClass="#{bean.inputValid?'':'inputInvalid'}"

If the component is invalid (validation has failed), then we will render inputInvalid CSS class. Otherwise, nothing is rendered.

This is the result when running the page (before invoking validation):

After validation:

As you can see the solution is pretty simple.

6 comments

  1. Oleg

    Hi Max,

    It’s a little bit strange way you proposed. We don’t need any beans. Simple use ‘component’ object which points to the current component.

    <h:inputText value="#{…}" styleClass="#{component.valid ? ” : ‘invalidField’}"/>

    That’s all.

    • Harish

      Hi Oleg,

      Do i can use style insted of style class.I dont know when to use component.valid.can u explain how to use component.valid in detail please.

      Thanks

  2. max

    @Oleg: thank you, agree, that’s the simplest solution if using JSF 2.

    Updated:
    If you need to style anything outside the component, such as label, then #{component.valid} won’t work.

    • Harish

      Hi max,

      Do i can use style insted of style class.I dont know when to use component.valid.can u explain how to use component.valid in detail please.

      Thanks

Leave a Reply