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.
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.
Field validation is an automated process of ascertaining that each field contains the correct value before the form is accepted. The concept is straightforward.
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.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With