Primefaces: Displaying Tabs with Validation Errors

I’ve been working on a page that makes use of the PrimeFaces TabView and ran into a problem with presenting validation errors. When a validation error occurs on submission on a tab other than the default tab, it was not clear to the user where the validation failure occurred. While I could bind the tabs to a backing bean and attempt to set the activeTabIndex, this did not cover the 90% scenario which is a field failing JSF validation or conversion. In these cases, the submission never makes it to the backend.

A more straight forward solution for me was jQuery. The following code snippets will result in the first tab with errors being selected when a validation failure occurs. It’s meant to work with PrimeFaces components with the ui-error-state styling, but could be adapted for the standard JSF components too.

Step 1: JavaScript Function

The following function locates any primefaces UI components with an error state and, if found, clicks the associated tab.

function showFirstInvalidTab() {
    var errorTab = $('div.ui-tabs-panel:has(.ui-state-error)').attr('id');
    if (errorTab) {
        var expression = 'a[href="#' + errorTab + '"]';
        var link = $(expression);
        if (link) {
            link.click();
        }
    }
}

Step 2: Call the Function

In my case, the page is being submitted in the traditional non-ajax way, so I used the jQuery document ready convention:

<script>
  $(function () {
   showFirstInvalidTab();
  });
</script>

But you can also attach it to your p:ajax oncomplete.

Enjoy.

One comment
  1. works great on PF 6.0.14, thx a lot.
    remember: this works only on tabViews with attribute dynamic=false
    ….

Comments are closed.