Using the Struts Framework for Validations

As I mentioned in one of my earlier posts, I started learning about Struts last week. Today I had to do some validations in the forms of the jsp pages and the first option that came to my mind was to use javascripts. However the people for whom I am doing this project, asked me to use the Struts framework instead. So after a healthy breakfast I set to get things done and opened google and typed “validations using struts”. 🙂

After a couple of hours and some common sense later, 🙂 I rigged up an application that used the struts framework for validations. I didn’t find one single tutorial that provided the basics. So I thought of combining what I got from many of them and put it here so that someone else like me can use this article to get the concept of validations under the belt and thank me whole heartedly. 😀

Well to start off with you need the jsp. The code below is of a sample jsp page.

The “s:head/” tag is quite important. It took me quite some time to understand the importance of it because I couldn’t get anything to work without that tiny little tag.

The next thing is the validations xml file. The struts framework uses xml files to do the validations. For each jsp there is an action class which handles the related business logic. An xml file should be created at the same location of the action class bearing the name action class name-validation.xml. For example if your action class’ name is SignInAction.java then your xml file should be named SignInAction-validation.xml. The code for the xml file is given below.

In the xml file the field-validator type is used to inform the struts framework what type of validations are required. For example if you put “email” there, the framework will check whether the entered email address is a valid one.

So that’s all folks. When you run the application try submitting the form without entering anything in the text boxes. The validations should pop up instantly. 🙂 Good luck!!!


Leave a Reply