damien535
damien535

Reputation: 637

Set focus to inputText on validation error

I want to set focus on inputText field in JSF when there is a validation error on that particular inputText. How can I implement this?

I thought validatorMessage on the inputText would do this out of the box but it appears not.

Upvotes: 1

Views: 4002

Answers (1)

BalusC
BalusC

Reputation: 1108632

There is no such default behaviour. You need to implement it yourself or use a 3rd party library for the job. Basically, during the render response you need to walk through the submitted form for all UIInput components and find the first one whose isValid() returns false and then store its client ID in the request map so that you can print it as a JS variable.

form.visitTree(VisitContext.createVisitContext(), new VisitCallback() {

    @Override
    public VisitResult visit(VisitContext context, UIComponent component) {
        if (component instanceof UIInput && !((UIInput) component).isValid()) {
            context.getFacesContext().getExternalContext().getRequestMap()
                .put("focus", component.getClientId(context.getFacesContext()));
            return VisitResult.COMPLETE;
        }

        return VisitResult.ACCEPT;
    }
});

Then you can use the following script to set the focus:

<h:outputScript target="body">
    var focus = '#{focus}';

    if (focus) {
        document.getElementById(focus).focus();
    }
</h:outputScript>

The JSF utility library OmniFaces has a reuseable component for this, the <o:highlight> (source code here and showcase demo here). It additionally also sets a styleclass on the invalidated inputs so that you can specify for example a different background color by CSS.

Upvotes: 2

Related Questions