Loading...
Important Notice - Forums is archived

To simplify things and help our users to be more productive, we have archived the current forum and focus our efforts on helping developers on Stack Overflow. You can post new questions on Stack Overflow or join our Discord channel.

Product icon
TUTORIAL

Vaadin lets you build secure, UX-first PWAs entirely in Java.
Free ebook & tutorial.

How to use Form.addValidator()

Benny Bräuer
10 years ago Feb 29, 2012 12:58pm
Javier Serrano
10 years ago Feb 29, 2012 1:27pm

Hi Benny,

If I understood right what you trying to do, you can solve the problem by setting the fields you want to validate immediately in immediate mode and adding a validator to them in order to validate them when the focus is gone, and, for the other fields, you should Override commit method of Form, and call "super.commit();" to do the validation of all other fields and implement your own logic to work with the values there.

For example:

Form form = new Form();
// Street 
TextField street = new TextField("Street");
street.addValidator(new StringLengthValidator("Wrong Street Lenght it should be 5 to 20 chars" 5, 20, false));
form.addField(street);

// Postal code that must be 5 digits (10000-99999)
TextField postalCode = new TextField("Postal Code");
postalCode.setColumns(5);
// Create the validator
Validator postalCodeValidator = new RegexpValidator("[1-9][0-9]{4}", "Postal code must be a number 10000-99999.");
postalCode.addValidator(postalCodeValidator);
postalCode.setImmediate(true); // The postalCode is in immediate mode i.e. is validated immediately
form.addField(postalCode); // the postal code is added to the form

// Add buttons to the form
HorizontalLayout okbar = new HorizontalLayout();
okbar.setHeight("25px");
form.getFooter().addComponent(okbar);
 
 // Add a Save (commit), Clear (discard) buttons to the form. 
okbar.addComponent(new Button("Save", form, "commit") ); // This calls commit in form and makes the validations
okbar.addComponent(new Button("clear", form, "discard")); // This calls discard in form and discard changes

HTH.

Javi

Last updated on Feb, 29th 2012
Benny Bräuer
10 years ago Feb 29, 2012 1:50pm