Barun
Barun

Reputation: 513

Css Style change with JSF Validation

I am working on a requirement to highlight fields that have failed in red after JSF server side validation. No javascript can be used for validation. Is there a method to link server side validation with css style changes?

Upvotes: 4

Views: 11830

Answers (2)

Drew
Drew

Reputation: 15408

The seam framework makes this very easy. Check this out: http://www.redhat.com/docs/manuals/jboss/jboss-eap-4.2/doc/seam/Seam_Reference_Guide/JSF_form_validation_in_Seam.html

Upvotes: 1

McDowell
McDowell

Reputation: 108899

You could do this with a managed bean:

public class ValidBean {

  private UIComponent myComponent;

  public UIComponent getMyComponent() {
    return myComponent;
  }

  public void setMyComponent(UIComponent myComponent) {
    this.myComponent = myComponent;
  }

  public String getErrorStyle() {
    FacesContext context = FacesContext
        .getCurrentInstance();
    String clientId = myComponent.getClientId(context);
    Iterator<FacesMessage> messages = context
        .getMessages(clientId);
    while (messages.hasNext()) {
      if (messages.next().getSeverity().compareTo(
          FacesMessage.SEVERITY_ERROR) >= 0) {
        return "background-color: red";
      }
    }
    return null;
  }
}

Request scope variable:

  <managed-bean>
    <managed-bean-name>validBean</managed-bean-name>
    <managed-bean-class>stylevalid.ValidBean</managed-bean-class>
    <managed-bean-scope>request</managed-bean-scope>
  </managed-bean>

Sample view:

  <f:view>
    <h:form>
      <h:inputText binding="#{validBean.myComponent}" styleClass="foo"
        style="#{validBean.errorStyle}">
        <f:validateLength minimum="6" />
      </h:inputText>
      <h:commandButton />
      <h:messages />
    </h:form>
  </f:view>

The component is bound to the backing bean. If error messages have been queued for the component, it overrides its CSS class settings with its style attribute.

Upvotes: 6

Related Questions