How to use Form.addValidator()

Hi all,

I would like to validate some fields of the form immediately, but some after submitting the form. The Java-Doc says for Form.addValidator():

Why? Wouldn’t it be useful to get access to all form values and allow a validation there? Or is there another way to do this?

Cheers
Benny

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

Hi Javi,

thanks, that should work too. Good to learn again something new :slight_smile:

Cheers,
Benny