You are viewing an old version of this page. View the current version.

Compare with Current View Page History

Version 1 Next »

In the Coding Actions lesson, we validated the username and password input with a few lines of Java code. Of course, in a larger application over time, even these few lines of code can become a maintiance buden.

Happily, the framework provides a validation framework that can confirm input "behind the scenes".

The Code

Like the mappings, validation is described through an XML document. The document is named after the Action being validated with a "-validation" suffix. Since we would like to validate the Login Action class, our document is named Logon-validation.xml.

Login-validation.xml
<!DOCTYPE validators PUBLIC 
"-//OpenSymphony Group//XWork Validator 1.0.2//EN" 
"http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">

<validators>
    <field name="username">
        <field-validator type="requiredstring">
            <message>Username is required</message>
        </field-validator>
    </field>
    <field name="password">
        <field-validator type="requiredstring">
            <message>Password is required</message>
        </field-validator>
    </field>
</validators>

Create a file named Login-validation.xml next to the Login.java class, and paste in the code.

How the Code Works

When the form is submitted, the framework checks for a validation for the target Action class, Login. Finding a Logon-validation.xml file, the framework creates a validation object for the class, based on the XML document.

Essentially, the validation is a set of Validator objects. The Validators are applied to the incoming properties. If a Validator fails, it's message is added to an internal queue. When all the Validators have fired, the framework sees that errors have been posted, and seeks the "input" result. The Action class method never fires.

Summary

The framework provides a validation framework. An set of validators can be associated with an input field. If validation fails, the framework can return to the input page and display the error messages.

(lightbulb) For more, see Validation in the Core Developers Guide.

  • No labels