Form validation in Struts 2

There are several ways to do server-side validation of your form with Struts 2. We will see how we can use validate() inside your action class to validate form inputs

First you can create web project with Struts support

I have the user.jsp which is having the HTML form to enter first name and the last name fields

Next I will create the bean class which has first name and last name fields with getters and setters

Next, we will create the action class . In this class we have refernce to the User bean class

In this class you have to create the validate() to do the validation. You can add the following method to above class

This will check the length of the first name field and error message is added using addFieldError() method

Now you can update the struts.xml file with following entry

If there is a error in vaidation process browser will load the user.jsp file again with error message

Now you can run the project and open the page in http://localhost:8080/validate/user.jsp

When you leave the first name blank and submit thr form you will get following screen with the error message