Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 5.3
Info

The example code for this tutorial, form_xml_validation, is available for checkout at https://svngithub.apache.org/repos/asf/struts/sandbox/trunk/struts2examples/com/apache/struts-examples

Introduction

In this tutorial we'll cover how to validate a user's input in form fields using Struts 2's XML validation methodology. In the Form Validation tutorial we discussed validating a user's input using the validate method in the Action class. Using a separate XML validation file gives you the ability to use validators built-in to the Struts 2 framework.

...

Code Block
titleXML Validator Required String


<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.3//EN"
 "http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">

<validators>
 <validator type="requiredstring">
 	<param name="fieldname">personBean.firstName</param>
 	<message>First name is required.</message>
 </validator>
</validators>

...

You can use the Struts 2 email validator to validate the user's input in the email field. Here is the validator node that is in the EditAction-validation.xml file.

Code Block
xml
xml
titleEmail Validatorxml


 <validator type="requiredstring">
 	<param name="fieldname">personBean.email</param>
 	<message>Email address is required.</message>
 </validator>
 <validator type="email">
 	<param name="fieldname">personBean.email</param>
 	<message>Email address not valid.</message>
 </validator>

...

The Struts 2 framework provides a powerful way to validate a user's form field input by using the regex validator. In the example application, we want to ensure the user enters the phone number in the format 999-999-9999. We can use a regular expression and the regex validator to enforce this rule.

Code Block
xml
xml
titleREGEX Validatorxml


<validator type="requiredstring">
 	<param name="fieldname">personBean.phoneNumber</param>
 	<message>Phone number is required.</message>
 </validator>
<validator type="regex">
	<param name="fieldname">personBean.phoneNumber</param>
	<param name="regex"><![CDATA[\d{3}-\d{3}-\d{4}]]></param>
	<message>Phone number must be entered as 999-999-9999.</message>
</validator>

...

In the example application, we want to ensure the user checks at least one of the car model check boxes. To enforce this rule we can use the fieldexpression validator. Here's the XML for that validator node.

Code Block
xml
xml
titleFieldExpression Validatorxml


<validator type="fieldexpression">
	<param name="fieldname">personBean.carModels</param>
	<param name="expression"><![CDATA[personBean.carModels.length > 0]]></param>
	<message>You must select at least one car model.</message>
</validator>

...