Versions Compared

Key

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

This tutorial assumes you've completed the Processing Forms tutorial and have a working form_processing project. The example code for this tutorial, form_validation, is available for checkout from the Struts 2 sandbox subversion GitHub repository: https://svngithub.apache.org/repos/asf/struts/sandbox/trunk/struts2examplescom/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.

...

Code Block
java
titlevalidate method
java

	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
xml
xml

<result name="input">/register.jsp</result>

...

So the following addFieldError method call:

Code Block
java
java

addFieldError( "personBean.firstName", "First name is required.")

...