Struts 2 validation types

Types of validations

There are three ways to perform validation in struts 2.

1) By Custom Validation Here, we must implement the Validateable interface (or extend ActionSupport class) and provide the implementation of validate method.

2) By Input Validation (built-in validators) Struts 2 provides a lot of predefined that can be used in struts 2 application to perform validation.

Struts 2 provides following bundled validators.

  • requiredstring validator
  • stringlength validator
  • email validator
  • date validator
  • int validator
  • double validator
  • url validator
  • regex validator

3) By Ajax Validation (built-in validators with ajax) If we don't want to refresh the page, we can use jsonValidation interceptor to perform validation with ajax.

Validators Scope

There are two types of Validators in Struts2 Validation Framework.

  1. Field Validators
  2. Non-field validators

Field validators, as the name indicate, act on single fields accessible through an action. A validator, in contrast, is more generic and can do validations in the full action context, involving more than one field (or even no field at all) in validation rule. Most validations can be defined on per field basis. This should be preferred over non-field validation wherever possible, as field validator messages are bound to the related field and will be presented next to the corresponding input element in the respecting view.

<validators>
  <field name="bar">
      <field-validator type="required">
          <message>You must enter a value for bar.</message>
      </field-validator>
  </field>
</validators>

Non-field validators only add action level messages. Non-field validators are mostly domain specific and therefore offer custom implementations. The most important standard non-field validator provided by XWork is ExpressionValidator.

<validators>
      <validator type="expression">
            <param name="expression">foo lt bar</param>
            <message>Foo must be greater than Bar.</message>
      </validator>
</validators>