Skip to Main Content
Jakarta Struts Cookbook
book

Jakarta Struts Cookbook

by Bill Siggelkow
February 2005
Intermediate to advanced content levelIntermediate to advanced
528 pages
12h 53m
English
O'Reilly Media, Inc.
Content preview from Jakarta Struts Cookbook

8.10. Adding a Custom Validation to a Validator Form

Problem

You need to add a custom ad hoc validation check to a Validator ActionForm.

Solution

Extend the ValidatorForm or ValidatorActionForm and override the validate( ) method, ensuring you call super.validate( ) to perform the Validator's validation. (See Example 8-14.)

Example 8-14. Extending the ValidatorForm

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.validator.ValidatorForm;

public final class MyForm extends ValidatorForm {
    private String foo;
    private String bar;

    public String getFoo( ) {
        return foo;
    }
    public void setFoo(String s) {
        foo = s;
    }
    public String getBar( ) {
        return bar;
    }
    public void setBar(String s) {
        bar = s;
    }
    public ActionErrors validate(ActionMapping mapping, 
                                 HttpServletRequest request) {
        // Perform validator framework validations
        ActionErrors errors = super.validate(mapping, request);
      
        // Add crossfield and business validations here
        if (!checkFooBarValid(foo, bar)) {
            errors.add("foo", new ActionError("errors.invalidFooBar"));
        }
        // additional validations ...

        return errors;
    }

    private boolean checkFooBarValid(Foo foo, Bar bar) {
        boolean valid = false;
        // perform custom validation
        valid = FooBarUtil.checkFooBar(foo, bar);
        return valid;
    }
}

If you're using a dynamic form defined in the struts-config.xml, extend the type being used (e.g., DynaValidatorForm ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Programming Jakarta Struts

Programming Jakarta Struts

Chuck Cavaness
Beginning Spring Framework 2

Beginning Spring Framework 2

Bruce Snyder, Sing Li, Anne Horton, Thomas Van de Velde, Naveen Balani, Christian Dupuis
Java Cookbook

Java Cookbook

Ian F. Darwin
Struts 2 in Action

Struts 2 in Action

J. Scott Stanlick, Chad Michael Davis, Donald J. Brown

Publisher Resources

ISBN: 059600771XSupplemental ContentErrata Page