Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

In the XML validation file (for this example that is EditAction-validation.xml), is this XML:

Code Block
XMLxmlXML
xml
titleXML Validator Required String

<!DOCTYPE validators PUBLIC
"-//OpenSymphony Group//XWork Validator 1.0.2//EN"
"http://www.opensymphony.com/xwork/xwork-validator-1.0.2.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
XMLxmlXML
xml
titleEmail Validator

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

<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="expression"><![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
XMLxmlXML
xml
titleFieldExpression Validator

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

...