How to do Form validation?


I want to do Form validation where I check two TextFields if they are not both empty. Both TextFields have no Validator assigned and .setRequired(false) is set. This way I can leave both fields empty. But the commit() should detect this case and report a message to the user. I did already searched the forum, but I only found a thread about using a derived Form class.

Her’s the code of my Form class:

  private class UserForm extends Form
    public UserForm()

    public boolean isValid()
      return false;

    public void validate() throws InvalidValueException
      TextField fn = (TextField) getField(FIELD_FIRSTNAME);
      TextField ln = (TextField) getField(FIELD_LASTNAME);
      String fnVal = (String) fn.getValue();
      String lnVal = (String) ln.getValue();
      if ((fnVal == null || fnVal.isEmpty()) && (lnVal == null || lnVal.isEmpty()))
        throw new InvalidValueException("First and lastname must not be both empty");

The problem arises when all other fields are valid and these two TextFields are both empty. The listed UserForm.validate() method is throwing an exception but I don’t get a message in the usual way, saying that a field must be filled. It would be great, if I could also mark these two fields with red stars.

How can I achive this?


Maybe you could only set those fields required when they are not empty, and again remove the requirement if they are both emptied? And if that doesn’t work for you, and it’s just the red exclamation mark beside the field you are looking for: if the field in question is an instance of AbstractComponent (as it should be), you can use abstractComponent.setComponentError(). Just set it to null again when you want to get rid of the alert.

Had a similar problem.
Just create a new Validator and add it to one of your textfields, e.g.:

public class MutualTextFieldsValidator extends AbstractValidator {
  private final Form form;

  public MutualTextFieldsValidator(Form form) { 
    super("First and lastname must not be both empty");
    this.form = form
  public boolean isValid(Object ignored) {
    TextField fn = (TextField) form.getField(FIELD_FIRSTNAME);
    TextField ln = (TextField) form.getField(FIELD_LASTNAME);
    return !((fnVal == null || fnVal.isEmpty()) && (lnVal == null || lnVal.isEmpty()));


fn.addValidator(new MutualTextFieldsValidator(myForm));

The only drawback ist that this validator is stateful…

@Anna and Jan,

thank you for your ideas. I think I will try Jans approach first.

Best regards


I am trying to build a simple form validation to make sure user enter something in the name text field. i have the followwing code

 tf = new TextField("name");
 tf.setRequiredError("Please enter a Name");

and on submit of a button i validate as given below. eventhough the validation fails it does not show the error message on the screen. am i missing something?

if (!rf.isValid()) {