membersound
membersound

Reputation: 86677

How to define validation constraints on TextFields in vaadin?

I have a TextField and add validation by field.addValidator(validator). I want to use the field both for editing an entity, as well as creating a new one.

Problem: when creating a new one, I would like to have more validators applied then when editing. Eg: creating an Account would require a UniqueAccountValidator added to the textfield.

But then, when I editing the account (with the same form), I'd like to skip only the UniqueAccountValidator as the object is not be be created new, but merged.

Is is possible to somehow tell a vaadin BeanFieldGroup or an AbstractField to skip certain validators in specific cases?

Upvotes: 2

Views: 586

Answers (1)

Laura
Laura

Reputation: 1602

You could create your own custom validator by implementing the Validator interface. There you can check what you need, like whether the entity is a new one or not.

Something like

public class MyValidator implements Validator {
    @Override
    public boolean isValid(Object value) {
        //check if your object is new or existent
        if(((BeanObject)value).getID()==null)){
        //non-existent entity, also check the unique account constraint 
             if(accountExists()) {
                   return false;
             }
             else {
                   return true;
             }
         }

         //common checks....
         {....} 

    }
....
}

Upvotes: 3

Related Questions