Home > Tutorials > Bootstrap > Validating Input |
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 maintenance burden.
Happily, the framework provides a validation framework that can validate input "behind the scenes".
Validation can be described through an XML document, or using annotations. The XML document is named after the Action being validated with a "-validation" suffix. Since we would like to validate the Logon Action class, our document is named Logon-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 Logon-validation.xml
next to the Logon.java
class, and paste in the code.
The first time a page displays, we wouldn't want the validation to fire. We should have a chance to enter the input before being told it's incorrect. One way to bypass validation is to refer to a special "input" method provided by the base ActionSupport class. To do that, we need to edit the Welcome page and the Logon mapping.
To indicate the changes, we'll use to indicate a line we are removing, and to indicated a line we are adding.
<li><a href="<s:url action="Logon"/>">Sign On</a></li>
<li><a href="<s:url action="Logon_input"/>">Sign On</a></li>
<action name="Logon" class="tutorial.Logon">
<action name="Logon_*" method="{1}" class="tutorial.Logon">
To open the Logon form, the Welcome page refers to Logon_input
.
Logon_*
action mapping.input
method on the Logon
Action class.input
method returns the result code "input".To submit the Logon form, the Login pages refers to Logon
.
Logon
.Logon-validation.xml
file, the framework creates a validation object for the class, based on the XML document.
The framework provides a validation framework. A 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. To bypass validation, a special "input" Action method can be invoked, instead of the default "execute" method.
For more, see Validation in the Core Developers Guide.
Next | |
---|---|
Prev |