Struts 2 Validation Example
Validation Login application
Struts 2 is very elegant framework that provides a lot of functionality to develop web based applications quickly. Here you will learn to write the form validation code in Struts 2 very easily. We will add the form validation code in our login application.
For validation the login application java script can be added to the jsp page or in action class, but Struts 2 provides another very easy method to validate your fields automatically. You can even use the same configuration file to generate client side script ( in next section we will see how to generate client side validation code).
The Struts 2 validation framework uses xml based configuration file. The file name should be <Your action class> -validation.xml. In our case our action class name is Login.java, so our validation configuration file will be Login-validation.xml. The Login-validation.xml will be saved into "webapps\struts2tutorial\WEB-INF\src\java\net\roseindia" directory. Here is the content of Login-validation.xml file:
In the above configuration file the field name corresponds to the ActionForm properties. For the username and password elements the requiredstring validation is applied and the message in the <message>....</message> tag is used to display the message if validation fails.
Compiling the application
To compile the application go to "\webapps\struts2tutorial\WEB-INF\src" directory and type ant command. The ant tool will compile the application for you.
Adding the link into index.html
Finally we add the link in the index.html to access the login form.
In the next section we will run and test the application.