Struts 2 Validations

In Struts 2 we can do validation in two ways:

1) validate method: We can implement validate method and can validate user input here.

In this method we can read the form values provided by user and check if the values are as per required format or not and then accordingly revert back to user or give call to execute method for doing further request processing.


Suppose we have a form page with below code:

 <s:form action="test" method="post">
    <s:textfield name="name" label="Name of Person" size="25" />
    <s:textfield name="age" label="Age of Person" size="15" />
    <s:submit name="submit" label="Submit" />

Then on action bean class, we have implementation of validate method:

public void validate()
      if (name == null)
         addFieldError("name","Name is mandatory.");
      if (age > 20 || age < 30)
        addFieldError("age","Age must be in between 20 and 30");

After filling form when user clicks on submit.

Validate method will get called in case the validation failed for any of the input failed then user will get returned to the same input page with message specified in the validate method.

If validation is successful then execution control will be passed to execute method implemented in the action and will do further request processing and return the response to user.

2) XML Validation: In this method we need to create a xml with name: actionname-validation.xml

And will place the same next to the action class.


<!DOCTYPE validators PUBLIC 
  "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
  <field name="name">
      <field-validator type="required">
          <message>Name is mandatory.</message>
  <field name="age">
     <field-validator type="int">
         <param name="min">20</param>
         <param name="max">30</param>
            Age must be in between 20 and 30