Versions Compared

Key

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

The example code for this tutorial, form_xml_validation, is available for checkout at https://svn.apache.org/repos/asf/struts/sandbox/trunk/struts2examples/Image Removed

Introduction

...

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.

xml
Code Block
xml
titleEmail Validator
xml

 <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
xmlxml
titleREGEX Validator
xml

<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.

xml
Code Block
xml
titleFieldExpression Validator
xml

<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>

...