Cheap VPS & Xen Server

Residential Proxy Network - Hourly & Monthly Packages

Bundled Validators


Struts 2 validation framework provides many built-in validators also known as bundled validators for email, string, int, double, url, date etc

So, we don’t need to provide explicit logic for email, double, url etc. For providing specific validation logic, we can use regex, which we will see later.

validation interceptor

It performs validation against the specified validation rules and adds the field-level and action-level error messages.

It works in conjunction with the workflow interceptor to display the error messages.

There is no parameter defined for this interceptor.


Advantage of Bundled validators

fast development because we don’t need to specify the common validators such as email date, string length etc.


Bundled validators

Struts 2 provides following bundled validators.

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

Two ways to use bundled validators

There are two ways to use bundled validators:

  1. Plain-Validator (non-field validator) Syntax
  2. Field-Validator Syntax

In the next page we will see the full example of bundled validators. Let’s now understand the difference between plain-validator syntax and field-validator syntax.


Plain-Validator (non-field validator) Syntax

Plain-validator syntax can be used for action level validator. In such case, a single validator can be applied to many fields.

But disadvantage of this approach is we can’t apply many validators to single field.

Let’s see simple example of plain-validator.

  1. <validators>
  2.     <!– Plain-Validator Syntax –>
  3.     <validator type=“requiredstring”>
  4.         <param name=“fieldName”>username</param>
  5.         <param name=“trim”>true</param>
  6.         <message>username is required</message>
  7.     </validator>
  8. </validators>

Field-Validator Syntax

The field-validator syntax can be used for field level validator. In such case, multiple validator can be applied to one field. For example, we can apply required and email validators on email field. Moreover, each field can display different messages.

But disadvantage of this approach is we can’t apply common validator to many field like plain-validator.

Let’s see simple example of field-validator.

  1. <validators>
  2.     <!– Field-Validator Syntax –>
  3.     <field name=“username”>
  4.           <field-validator type=“requiredstring”>
  5.             <param name=“trim”>true</param>
  6.             <message>username is required</message>
  7.        </field-validator>
  8.     </field>
  9. </validators>

Which validator syntax is better?

It is recommended to use field validator by apache struts because it provides more flexibility.

Comments

comments