Info |
---|
This tutorial assumes you've completed the Processing Forms tutorial and have a working Form_Processing_Struts2_Ant (or Form_Processing_Struts2_Mvn) form_processing project. The example code for this tutorial, Form_Validation_Struts2_Ant or Form_Validation_Struts2_Mvn, is available on Google Code - http://code.google.com/p/struts2-examples/downloads/list. After downloading and unzipping the file, you'll have a folder named Form_Validation_Struts2_Ant (or Form_Validation_Struts2_Mvn). In that folder will be a README.txt file with instructions on now to build and run the example applicationform_validation, is available for checkout from the Struts 2 GitHub repository: https://github.com/apache/struts-examples. |
Introduction
In this tutorial we'll explore using Struts 2 to validate the user's input on a form. There are two ways you can use Struts 2 to do form validation. This tutorial will cover the more basic method, where the validation is included in the Struts 2 Action class. The code provided in this tutorial may be added to the Processing Forms example or you can download this complete example from Google Code - http://code.google.com/p/struts2-examples/downloads/list.
Tip |
---|
The Struts 2 user mailing list is an excellent place to get help. If you are having a problem getting the tutorial example applications to work search the Struts 2 mailing list. If you don't find an answer to your problem, post a question on the mailing list. |
...
Add the following validate method to Register.java (the Action class).
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
public void validate(){
if ( personBean.getFirstName().length() == 0 ){
addFieldError( "personBean.firstName", "First name is required." );
}
if ( personBean.getEmail().length() == 0 ){
addFieldError( "personBean.email", "Email is required." );
}
if ( personBean.getAge() < 18 ){
addFieldError( "personBean.age", "Age is required and must be 18 or older" );
}
}
|
...
To handle the return value of "input" we need to add the following result to our action node in struts.xml.
Code Block | ||||
---|---|---|---|---|
| ||||
<result name="input">/register.jsp</result>
|
...
So the following addFieldError method call:
Code Block | ||||
---|---|---|---|---|
| ||||
addFieldError( "personBean.firstName", "First name is required.")
|
...