Menu

JSF page: focus on error input when on error only

Goal

To focus on an input field when there are validation errors and only on that situation

Description

This recipe is about a simple way to use the focus component from Primefaces to focus on input fields only when that input’s validation failed.

Primefaces has an attribute minSeverity which specifies the minimum severity for a component to obtain focus that, when not specified, has error as default. However, that is not enough to do the trick of not focusing at all in any component unless one of the fields in the page had their validation failed

How to

Simply put, we use a focus component which is shown conditionally, based on the expression language #{facesContext.validationFailed}

The only additional important thing to consider here is that the focus component needs to be refreshed when the form or a specific part of that form is processed. So, wrap the part of the form you want to process inside a panelGroup component with a specific id which is updated after the submission or, if you are using Primefaces 5.1, use the fragment component.

Explanations

The trick of this recipe is to present a focus component on the page only the page validation failed. That, together with the built-in features of the focus component will do the trick. Just remember to make sure the focus component is refreshed together with the part of your page that needs to get a focus on a potentially invalid field.