Struts Tutorial

Struts Validation (Client and Server Side)

Before We Start

In this tutorial we will show you how to use the Struts Validation Framework. This framework is very powerful but at the same time can be very complex. Even implementing a simple validation, for example, checking if a value was entered, can be a tedious task. However, we are not going to get into any complex theory behind Struts validation. There are plenty of books that do that. But, we will show you how to add simple validation to your application and hopefully you will be able to take it from there.

For this tutorial, we are again going to continue working with our guessGame application. If you already have it, great; if not, download it, unzip it in the Eclipse project directory, and import it into Struts Studio. Now, we are ready to start!

Adding Validation to the Project

Our first step will be to create the validation itself. Once we have it ready, we can choose if we want to use client or server side validation. To switch from one approach to another requires very minor changes. In this tutorial we will show both ways.

To proceed, we will first add the ValidatorPlugIn to struts-config.xml file. Then, open an editor for the struts-config.xml file and switch to the Tree view. Now, right-click plug-ins and select Create Special Plug-in/Validators. This will add two XML validation files to your project. If you look at the source, you should see the plug-in that we just added at the bottom. This tells the Struts runtime where to look for your validation definitions.

Next, we need to create a properties file with default error messages. Right click JavaSource/sample and select New/New Properties File. Call the file applResorces.

Next, we need to add this file to our application. Switch to the Tree view of struts-config.xml. Right-click resources/Define Message Resource... . We only need to supply the first field. Click the Change button for the parameter field and browse to guessGame/sample/applResources.properties. Select the file and click Ok and then Finish. We have now added the properties file to our application.

There is one last step before we start with the actual validation. Right-click sample.applResources and select Add Default Error Messages. After this, save all changes in the project. We are now ready to define our actual validation rules.

Before this, let's run our application just once to see what validation we want to add. Start Tomcat server. Then switch to the Diagram view of the struts-config.xml file and right-click the start Forward and select Run.

Creating Validation Rules

We will add two validation rules to our application. First, we'll make sure that some input was entered. Second, we'll make sure that the value entered is an integer and is between 0 and 100.

Locate and open the WebContent/WEB-INF/validation.xml file (make sure you open it with the default editor, the Struts Studio XML Editor). You should now see the Struts Studio Validation editor. This visual editor allows you to define validation rules instead of typing XML code manually in the struts-config.xml file.

Right-click formset(default) and select Create Form. This will be the Form bean (ActionForm) that captures input from the JSP page. Type in "MakeGuessForm" and click Finish.

Now, right-click MakeGuessForm and select Create Field. We now need to create the field that we want to validate. Type in "guessNumber" and click Finish. Your editor should look like the image below.

The next step is to create validation rules. Right-click guessNumber and select Add Validation Rule. This screen allows us to add validation rules. Note that validation rules are taken from the validation-rules.xml file. You could, of course, create your own validation rules and then simply select your validation file.

Select required from the left pane and click the Add-> button. This rule will make sure that a user enters something on the web page.

Click Ok. Now we need to create what we want to display when the users enters nothing.

Select required under guessNumber and click Add in the middle window ( Arg - Replacement Value for Message Template). Don't worry if you don't yet understand what is happening. It all should become more clearer as we progress.

All values will stay the same. We just need to enter something for Key. Click Change....

You should now see our applResources file and the default error messages that we have added. We will create a new key for this validation rule.

Click Add and create the property described below, click Finish when done.
namevalue
Nameinput.required
ValueInput number

The new entry should now appear in the list. Go ahead and click Ok to exit from this screen. We should be back at this screen.

Let's see what we have here.
namevaluedescription
NamerequiredName of the validation rule that we selected from a list of available rules to use (from validation-rules.xml). This validation rule has the following error message: {0} is required.
Argarg0This will be replaced with the value of key below during runtime. In other words, the error message has the following form {0} is required and so arg0 will be looked up via the input.required key and its value will be inserted instead of {0}.
Keyinput.requiredThis is the key to look up the message to replace {0}.
ResourcetrueThis is where to look for a replacement message. If true, look inside the resource file.
Now, save all changes.

So, we have created our first validation rule. We'll go ahead and start with client-side validation and see how it works. We'll make some minor changes to our JSP files and run the application.

Open the /pages/start.jsp page. Only two minor changes are required. Add the following right after the <html:html> tag:

<head>
  <html:javascript formName="MakeGuessForm"/>
</head>
and then modify this line (changes in blue):
<html:form action="/makeGuess.do" onsubmit="return validateMakeGuessForm(this)">
That's all that needs to be done to the JSP page to add client-side validation. We also have /pages/nomatch.jsp, go ahead and make the same changes to that page.

That's it. We're ready to run the application. First, save all changes. Recompile the whole project, during compilation applResources will be copied to classes folder so that runtime can find it. Restart Tomcat server.

Launch the application in a web browser. Go ahead and hit Guess without entering anything. You should see the error message below.

Adding a Second Validation Rule

We are ready to add another validation rule. This rule will check if the value entered is between 0 and 100. It will also check if the value entered is an integer.

Go ahead and open the validation.xml file in the Formsets view as shown below. Right-click guessNumber and select Add Validation Rule.

Scroll down in the left pane and select the intRange rule and add it to the right pane. Click Ok when done. So now we have two rules.

In the middle pane (Arg - Replacement Value for Message Template) click Add. Select Change.... The intRange validation rule uses this message template: {0} is not in the range {1} through {2}.

Now, we need three replacement values for each of the {} arguments. The {0} should be the name of the field and {1} and {2} should tell us the range.

So for, {0} we will use an existing message. Go ahead and select input.required. In other words, {0} will be replaced by Input number. Click Ok twice to exit.

Now we need values for {1} and {2}. Click Add again in the middle pane. We are going to add another argument but this time it will not be taken from the resource file. We will create a Validator Parameter as the replacement value for {1}.

Enter the following values:
namevaluedescription
NameintRangeName of the validation rule that we selected from a list of available rules to use (from validation-rules.xml).
Argarg1This will be replaced by lower range limit.
Key${var:min}This tells to look for replacement value in the vars.
ResourcefalseWe are not going to look for replacement value in the resource file.

Click Ok when done. We now need to add another arg for arg{2}. Click Add again and create this entry:
namevaluedescription
NameintRangeName of the validation rule that we selected from a list of available rules to use (from validation-rules.xml).
Argarg2This will be replaced by the upper range limit.
Key${var:max}This tells us to look for a replacement value in the vars.
ResourcefalseWe are not going to look for replacement value in the resource file.

Click Ok when done. Now we have our three arguments that are going to replace { } during runtime. We are not done yet, because we still need to define ${var:min} and ${var:max}.

Click Add in the lower pane (Var - Validator Parameter). This is where we are going to define our min and max var values. Create the following two entries:
namevalue
Var-namemin
Var-value0
And this one:
namevalue
Var-namemax
Var-value100

After you create these Validator Parameters, you should have this view. We are actually done. Save all changes, recompile the whole project and restart Tomcat server.

Now hit Guess without entering anything. You should see the first error message. Enter a value that is not in the range, for example -5. You should get this error.

Please note that we have only modified one of the JSP files, start.jsp. You need to modify nomatch.jsp as well to have client side validation on that page.

Using Server-Side Validation

To use server side validation instead of client side we only need to make some minor changes because we are still going to use the same validation rules that we already created.

We first need to modify the start.jsp file. First delete the part in blue, becuase we are not going to be calling JavaScript anymore. Instead, we are going to be sending the request to the server and validate our input there.

<html:form action="/makeGuess.do" onsubmit="return validateMakeGuessForm(this)">
you should have this left:
<html:form action="/makeGuess.do">
Now, add this line right before </html:form> tag (in blue):
...
<font color="blue"><html:errors /></font><br/>
<html:form action="/makeGuess.do">
...

We are done making changes to this JSP page. Save all changes. The last thing that we need to do is to make some minor changes to the MakeGuessForm.java file. Open MakeGuessForm.java and make the following changes.

First, comment out the validate() method.

...
/***
public ActionErrors validate(ActionMapping actionMapping, HttpServletRequest request) {

  return null;
}
***/
...
and, second, modify the base class that our form extends, as shown below in blue.
...
public class MakeGuessForm extends org.apache.struts.validator.ValidatorForm
...

The last thing that we need to do is to modify properties for our Action. On the Web Flow diagram, right-click the /makeGuess Action and select Properties. For the input property, click at the end of the value field to open a browse editor.

In the Pages tab, browse to guessGame/WEB-ROOT/pages/start.jsp. Click Ok. The input parameter tells Struts runtime where to go if validation fails, in other words if an error has occurred. In our example, we are going back to the same page to show the error message. Click Close.

We are done. Save all changes. Recompile the whole project and restart Tomcat server. Go ahead and run the application in a web browser. Enter a negative value, for example -9. You should see the following page.