Download Source | View Demo
One of the core Struts2 features is its comprehensive built in validation support. Struts2 supports a wide range of validation rules including regular expression validation. Data type validations supported are - conversion,date,double, email, expression, fieldexpression, int, regex, required, requiredstring,stringlength, url and visitor.
To use any of the predefined validators, no initial configuration is needed. Validation is implemented using a ValidationInterceptor which is configured in the default interceptor stack.
Struts2 supports serverside and client side validations. It also supports Ajax validation. Validations can be applied to specific form fields or it can be non field validations. It is also possible to create custom validators for any project specific validation requirements.
In this post, I will look at how simple server side validation can be implemented in Struts2.
We have a requirement to implement a screen which captures customer information. For simplicity, let us assume that this screen fields require the following validation.
Name : String with a maximum length of 50 characters
Age : Integer between 1 and 120
Email : A valid email address
The sample screen is given below.

First we need an action class to display the new customer form.
CustomerNewAction.java - Action class to dispatch to customer data capture form
customer_new.jsp - Form to capture customer data
One important thing to note here is the use of s:head tag. This injects the required stylesheets for error display after validation. The default theme used here is xhtml.
As you can see the input form is submitted to CustomerSaveAction. This will save the data and will dispatch to a page customer_save_success.jsp.
CustomerSaveAction.java - This is responsible for saving customer data. In this example, actual save is not implemented.
customer_save_success.jsp
Now we need to apply the declarative validation to CustomerSaveAction. To do that create a file CustomerSaveAction-validation.xml in the same folder which contains CustomerSaveAction.java. In Struts2, validation rules for an action class X is saved in a file X-validation.xml.
CustomerSaveAction-validation.xml
For more details on each of the validators and their parameters, please see here.
Let us connect everything together using struts.xml. Note the extra result tag (input) for CustomerSaveAction. It indicates the page to be displayed in case of input error.
struts.xml
web.xml
To invoke this sample, access the URL http://localhost:8080/struts2/CustomerNewAction.action. This is how the screen appears after validation,
