Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Conditional Validation On Submitting Form Component (Non-Nested Form Approach)

Say we have four form components within the same form:

  1. name A
  2. description A
  3. name B
  4. description B

Sometimes we want the whole form to validate/process (Button C), but sometimes we only want "A" form components to validate/process (Button A). One way to accomplish this is to:

Code Block

final TextField nameA = new TextField("name", ...);
final TextField descriptionA = new TextField("descriptionA", ...);
final TextField nameB = new TextField("nameB", ...);
final TextField descriptionB = new TextField("descriptionB", ...);

// the validators can be anything, but for simplicity we just use required
nameA.setRequired(true);
descriptionA.setRequired(true);
nameB.setRequired(true);
descriptionB.setRequired(true);

final Button buttonA = new Button(id) {
    public boolean onSubmit() {
        // because we overrode the form processing we need to handle validation/processing on the components ourselves
        nameA..validate();
        descriptionA.validate();
        if(!nameA.isValid() || !descriptionA.isValid()){
                // didn't validate so we stop processing (validation errors will be displayed provided we are using a FeedbackPanel or similar)
                return;
        }
        // TODO : now we have the updated values/models so we can perform whatever button A is supposed to do
    }
});
// set the form processing to false so that no validation/processing will occur on the form when button A is clicked
buttonA.setDefaultFormProcessing(false);

final Button buttonC = new Button(id) {
    public boolean onSubmit() {
        // TODO : all validation passed because form processing is true so we can perform whatever button B is supposed to do
    }
});

Conditional Validation On Each Form Component (Nested Form Approach)

Flagging a form field as "required" is the most common kind of validation. In most cases, this can be specified statically as follows:

...