Time for action – validating user input
We can run a TestSet
instance only if the user selects one. Follow these steps to add a proper validation:
- Implement your
initButton
method to match this code:private void initButton() { button.addClickListener(new ClickListener() { @Override public void buttonClick(ClickEvent event) { if(isValid()) { runSelectedTest(); } } }); }
- Now implement your
validate
method. Here is how we validate:public boolean isValid() { combo.setComponentError(null); textField.setComponentError(null); boolean isValid = true; if(combo.getValue() == null) { combo.setComponentError( new UserError("Select a test from the list.")); isValid = false; } if(textField.getValue().toString().isEmpty()) { textField.setComponentError(new UserError( "You must introduce the number of iterations to execute")); isValid = false; } return isValid; }
What just happened?
For the button listener, it's the same as in previous chapter. We have a button and we want to respond to click events, so we add ClickListener
, using an anonymous class.
As you can see, if the isValid
method returns true
, we proceed to run the selected test. First two lines of the method are for clearing any error we may have added to the components in previous executions of the isValid
method itself. Then, we declare a flag that will tell us whether the components have valid values or not. If the selected value in combo
is null, we add an error message to the component using the following code line:
combo.setComponentError(new UserError("Select a test from the list."));
setComponentError
expects an instance of ErrorMessage
. UserError
is an implementation of the ErrorMessage
interface that allows us to show an error message on the component. Usually, the component will show an error indicator. If the user places the mouse cursor over the component, a tooltip will appear showing the error text:
A similar logic is used to show an error over textField
if the users left it empty.
Note
Vaadin comes with three flavors of errors, UserError
, SystemError
, and CompositeErrorMessage
, as follows:
UserError
is an error that we, programmers, generate as a result of validationsSystemError
is used where there is a problem in the system (for example, an uncaught exception)CompositeErrorMessage
allows you to show multiple error messages
Layout spacing
We have our components ready. We know how they respond to events (clicks and value changes) and how they communicate. We still have to know how the tests are executed and how the results are shown. But first, let's incorporate all those components into the main layout.