Simple Validation of Textboxes

I have a simple problem for which most web frameworks offer a fairly straightforward solution. However, for Vaadin, all the Information I find on this topic seems to be outdated and/or overly complicated.

Let’s say I have a couple of Textboxes. For some, I have set setRequired(true) and for others, I added some RegExpValidators. Since I don’t need to, I’m currently not using any databinding, FieldGroups, BeanValidators etc.

Now what would be the cleanest (= requiring the least amount of code and Memory/CPU) to a) validate those fields and b) display the respective error messages upon clicking a button? Do I need to use FieldGropus? Do I iterate the fields?

Any answers and examples would be highly appreciated, thanks!

Hi Philipp

Almost applications do use databinding/fieldgroups => that’s why the documentation is oriented towards that approach.

However, it’s very simple to do.

Assuming all the textboxes are on the same layout, something like the following would suffice; Note that setComponentError is on AbstractComponent, not Component interface. I have yet to find a component that doesn’t extend AbstractComponent - but you might want to handle that case as well.

If the components are on different layouts (or child layouts), you’ll need to handle obtaining the fields to validate differently; essentially, you simply need to call field.validate(), catch InvalidValueException to get the validation error message, and AbstractComponent#setComponentError to, um, set the components error message.

HTH,

Cheers,

Charles.

    for (Component component : layout) {
      if (component instanceof Field && !component.isReadOnly() && component.isVisible()) {
        try {
          ((Field) component).validate();
        } catch (Validator.InvalidValueException e) {
          UserError componentError = new UserError(e.getHtmlMessage());          
          ((AbstractComponent) component).setComponentError(componentError);
        }
      }
    }

Thanks, that works just fine!

Just out of curiosity, do you think it would be more reasonable to use a FieldGroup for this, even if I don’t need most of it’s functionality? If so, could you point me to a minimalistic way to do so?

If you don’t need much of it’s functionality, I can’t see much point in using it. FWIW, my project is still using the deprecated Form, and I am about to embark upon working out the best way of handling forms/fields/binding/validation etc…

I would recommend reading it’s FieldGroup’s source though (and, indeed, Form etc) - it’s pretty clear how it does most of it’s stuff.

Cheers,

Charles.