Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 535
Landei Avatar asked Apr 25 '14 07:04

Landei


People also ask

What is cross field validation?

In simple words, making sure our data is correct by using multiple fields to check the validity of another. In fancier terms, this process is called Cross Field Validation. Sanity checking your dataset for data integrity is essential to have accurate analysis and running machine learning models.

What is field validation?

Field validation is an automated process of ascertaining that each field contains the correct value before the form is accepted. The concept is straightforward.


2 Answers

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.

like image 50
nexus Avatar answered Nov 14 '22 23:11

nexus


You can try to create your own validator by implementing Validator interface:

final TextField field = new TextField("Name");
field.addValidator(new MyValidator());

class MyValidator implements Validator {
            @Override
            public void validate(Object value) throws InvalidValueException {
                if (!isValid(value))
                    throw new InvalidValueException("fail");
            }

            @Override
            public boolean isValid(Object value) {
                //some code
            }
}
like image 35
user3551612 Avatar answered Nov 15 '22 01:11

user3551612