Form validation works by asking each field to validate itself. A field obviously can have a validator. The result is that each field in the form validates itself without knowing anything about what other fields are on the form.
I need to do a validation that checks to see if either field A or field B is set. One of these two fields must be set, or else I need to report an error back to the user.
What’s the best way to accomplish this? I don’t see an obvious one–my current thought is to override form.validate() and perform the validation in there, but then I’m not sure how to mark the fields that have failed validation.
You could create your own validator (implements Validator) for let’s say Field A and add Field B as parameter to the constructor of the validator. That way, you can use Field B (and it’s value) to implement the isValid() and validate() methods.
Jan , I tried to apply your approach, but I can’t really realize it.
Suppose we have two fields
A and
B . And suppose we want to write a trivial validator
V , that should check that both fields are not empty before the form can be committed.
Let’s assume
V is assigned to both fields
A and
B (assigning to one of them has the same side effect) and both fields are empty by default when form is loaded. Now user wants to enter something into field
A .
V does not accept the value, because
B is empty.
The value should be accepted into
A and
B and then checked as a whole. This can only be done on form submission, not on per-field basis. That is why I think that
com.vaadin.ui.Form should not block
addValidator() .
I had your same problem. I resolved implementing a Validator ad an inner class of my form-derived class, that can access other field’s values. In this way, the A validator can read value of the B field and do its cross-validation (same for B ). The error notification can rely on the default Vaadin notification mechanism.