I am looking for some guidance/opinion on the best way forward to add field error highlighting in JSF 2.0. So far I have successfully implemented using Cagatay's example with a few minor adjustments to logic.
String styleClass = ( String ) uiInput.getAttributes().get("styleClass");
//Check the valid flag
if ( !uiInput.isValid() )
{
//Component already has a styleclass
if ( styleClass != null )
{
//check if it's already highlighted
if ( !styleClass.contains("ui-input-invalid") )
{
//if not add the error class to it
styleClass = styleClass + " ui-input-invalid";
//and put the new styleclass back on the component
uiInput.getAttributes().put("styleClass", styleClass);
}
} else
{
//no current style class so just add the error class
uiInput.getAttributes().put("styleClass", "ui-input-invalid");
}
} else //component is valid so we might need to remove a highlight
{
//component has a styleclass
if ( styleClass != null )
{
//check if it is already highlighted
if ( styleClass.contains("ui-input-invalid") )
{
//remove error class from the string
styleClass = styleClass.replace("ui-input-invalid", "");
//and put the new styleclass back on the component
uiInput.getAttributes().put("styleClass", styleClass);
}
}
}
I have also used the suggestion of adding el to each component's styleclass - styleClass="#{component.valid ? '' : 'ui-input-invalid'}"
.
Both methods work like a charm when used in conjunction with Bean Validation JSR303. However I also have 2 additional validation stages. 1 to validate the form as a whole i.e. correct combination of fields and 1 to validate our general business rules once the field and form validation is successful. In order for these stages to also add the highlighting I need to do some manual work. For both highlighting approaches I have to manually set the component(s) valid flag to false. To have access to the component I have bound it to its own object in the form vo. Now for Cagatay's example I need to add all of the components to a List and then pass this list to the highlighting method. If I use the styleclass approach I don't have to worry about a component list and passing to a highlighting method. This seems the better approach to me however I'm a little concerned that it is adding logic to the JSF page which is something I want to stay away from.
What do you feel is the best approach or is there another way I am not aware of? Also I assume there is no other way of setting the valid flags without binding to the component? At the moment I having to bind every component so I can set its valid flag.