This blog shows how to add validation to the IconTabBar in SAP UI5 by creating a custom control.
SAP UI5 provides a nice control out of the box to create screens with tabs: IconTabBar. Indeed, with very little code, it is easy to create a screen such as below:
Therefore, within many of our UI5 projects, we use this control. At some point we ended up needing an event that would occur right before the change of tab and then authorize the change of tab or not. Such event could be used for example for validation. Unfortunately, after loooking at the SAP UI5 documentation, it appears that the IconTabBar comes only with two events.
Since no such event exists, we had to create our own custom control that extends the standard and provides such functionality.
Within this tutorial, we provide a very simple application that contains one view with a tab container that holds two tabs. The first one contains only one input field and the user can only navigate to the second one once he has entered hello in the input field.
In the case below, when the user clicks on the Second Tab, nothing happens:
Yet, if he enters the right word
He can then go to the second tab
Rather than describing all the steps to re-create the project, we’d suggest you import the project directly from the zip file within the WebIDE. You can download the zip file here:
Once Imported, you should have the following:
The project contains only one XML view that uses the custom control defined in the control folder in the file IconTabBar.js.
This file defines two custom controls, an IconTabBar and an IconTabHeader. Within the IconTabHeader, we found that the standard method setSelectedItem would be the perfect candidate to inject the validation and control whether the tab should be selected or not.
This new method, validateTab, is called line 16 and depending on what it returns, true or false, will either exit the function or call the default one from the original control (line 20).
The new IconTabBar only redefines the aggregation making sure it uses the new IconTabHeader control we just defined. We also had to redefine the _getIconTabHeader to enforce it was using the new IconTabHeader.
This custom control can then be used within any view and only requires the corresponding controller to define the validateTab method. For instance, we defined it in the init method of the View1’s controller.
The view itself is pretty straightforward:
Make sure you include the xmlns tag that is used to reference the custom control.
That's it! You can download the example project for import into the Web IDE here: