APIs for the Internet of Things

Max Katz

Subscribe to Max Katz: eMailAlertsEmail Alerts
Get Max Katz via: homepageHomepage mobileMobile rssRSS facebookFacebook twitterTwitter linkedinLinkedIn

Related Topics: Java EE Journal, Java Developer Magazine

Blog Feed Post

How to Highlight a Field in JSF When Validation Fails

Highlighting an input field that failed validation (or conversation) is a common UI practice today

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:

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:

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

Everything important happens here:


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.

Read the original blog entry...

More Stories By Max Katz

Max Katz heads Developer Relations for Appery.io, a cloud-based mobile app platform. He loves trying out new and cool REST APIs in mobile apps. Max is the author of two books “Practical RichFaces” (Apress 2008, 2011), DZone MVB (Most Valuable Blogger), and is a frequent speaker at developer conferences. You can find out what Max is up to on his blog: http://maxkatz.org and Twitter: @maxkatz.