Search code examples
javavalidationvaadinbean-validationvaadin7

Strategy for cross field validation in Vaadin


Field validation works easy enough in Vaadin, but you can't use it to check for relations between fields (e.g. that a joining date must be before a leaving date), which is really annoying. So I added standard class level validation using JSR 303 which can do this. This works fine.

But I can perform this cross field validation only after I have commited the fields. That means that the bean already contains all field changes, and in case of a validation issue I need a possibility to "go back" to the valid state before the field commits (or to force somehow a "reload" of the bean), else I'm stuck with the changes, e.g. if the user decides to cancel the edit action.

Of course I could save all field contents before, and reset the state manually, but given that Vaadin does exactly the same in case of simple field validation I'd like to reuse that mechanism. But looking at the Vaadin code, I'm not very confident I can figure out what to do, and to do it right.

Please give me some hints how to deal with this problem without reinventing the wheel.


Solution

  • You can add a commit handler to your FieldGroup. This allows you to check before/after commitment:

    binder.addCommitHandler(new CommitHandler() {
    
        @Override
        public void preCommit(CommitEvent commitEvent) throws CommitException {
            // TODO throw new CommitException() if your validation fails
        }
    
        @Override
        public void postCommit(CommitEvent commitEvent) throws CommitException {
            // TODO throw new CommitException() if your validation fails
        }
    });
    

    So it should be possible to "cross field" validation.