3

I'm going through validation in JSF and I see lots of examples of very basic logic. Frankly, I put them in the same category where the HelloWorld examples go. I can't imagine placing error messages in xhtml files, using a separate validation method for each validated field or employing bean validation.

What I want to do, is have a single method on the backing bean that will execute validation for each field, logging error messages driven by keys in i18n property files.

Can this be done? If so, how do we register that method as validating method, how do we obtain submitted field values for evaluation, and how do we register error messages?

1 Answer 1

0
<h:inputText id="username" value="#{bean.username}" label="UserName" binding="#{bean.component}"/>
<h:message for="username" />
<h:commandButton value="Submit" action="#{bean.actionMethod}" />

In your bean class,

private UIComponent component;

public UIComponent getComponent() {
    return component;
}

public void setComponent(UIComponent component) {
    this.component = component;
}

public String actionMethod() {
    if (!validate()) {
        return null;
    }
    // do your action method logic
}

private boolean validate() {
    FacesContext context = FacesContext.getCurrentInstance();

    //do validation for your fields and add to faces messages
    FacesMessage msg = new FacesMessage(severity, summary, detail);
    context.addMessage(component.getClientId(), msg);

    // do for other fields

    return status;
}

Refer this to get component client id

How to add a message to a specific component from JSF backing bean

1
  • I believe that the component is used to tie an error message to a particular field so it can be displayed next to that field. I don't have such requirements - all my error messages are to be displayed at the top of the form. Hence, I have not used the component. The approach you are showing (validate() within actionMethod()) answers my question, so I am accepting this, as a solution. Thanks.
    – jacekn
    Dec 30, 2013 at 5:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.