blob: c78ef71fce7fad480556ed34f3cc8e719138e367 [file] [log] [blame]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<meta name="Date-Revision-yyyymmdd" content="20140918"/>
<meta http-equiv="Content-Language" content="en"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Form validation using XML</title>
<link href="//fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700,400italic,600italic,700italic" rel="stylesheet" type="text/css">
<link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
<link href="/css/main.css" rel="stylesheet">
<link href="/css/custom.css" rel="stylesheet">
<link href="/css/syntax.css" rel="stylesheet">
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="/bootstrap/js/bootstrap.js"></script>
<script type="text/javascript" src="/js/community.js"></script>
<!-- Matomo -->
<script>
var _paq = window._paq = window._paq || [];
/* tracker methods like "setCustomDimension" should be called before "trackPageView" */
/* We explicitly disable cookie tracking to avoid privacy issues */
_paq.push(['disableCookies']);
_paq.push(['trackPageView']);
_paq.push(['enableLinkTracking']);
(function() {
var u="//analytics.apache.org/";
_paq.push(['setTrackerUrl', u+'matomo.php']);
_paq.push(['setSiteId', '41']);
var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
g.async=true; g.src=u+'matomo.js'; s.parentNode.insertBefore(g,s);
})();
</script>
<!-- End Matomo Code -->
</head>
<body>
<a href="https://github.com/apache/struts" class="github-ribbon">
<img decoding="async" loading="lazy" style="position: absolute; right: 0; border: 0;" width="149" height="149" src="https://github.blog/wp-content/uploads/2008/12/forkme_right_red_aa0000.png?resize=149%2C149" class="attachment-full size-full" alt="Fork me on GitHub" data-recalc-dims="1">
</a>
<header>
<nav>
<div role="navigation" class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" data-toggle="collapse" data-target="#struts-menu" class="navbar-toggle">
Menu
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a href="/index.html" class="navbar-brand logo"><img src="/img/struts-logo.svg"></a>
</div>
<div id="struts-menu" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="dropdown">
<a data-toggle="dropdown" href="#" class="dropdown-toggle">
Home<b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li><a href="/index.html">Welcome</a></li>
<li><a href="/download.cgi">Download</a></li>
<li><a href="/releases.html">Releases</a></li>
<li><a href="/announce-2024.html">Announcements</a></li>
<li><a href="http://www.apache.org/licenses/">License</a></li>
<li><a href="https://www.apache.org/foundation/thanks.html">Thanks!</a></li>
<li><a href="https://www.apache.org/foundation/sponsorship.html">Sponsorship</a></li>
<li><a href="https://privacy.apache.org/policies/privacy-policy-public.html">Privacy Policy</a></li>
</ul>
</li>
<li class="dropdown">
<a data-toggle="dropdown" href="#" class="dropdown-toggle">
Support<b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li><a href="/mail.html">User Mailing List</a></li>
<li><a href="https://issues.apache.org/jira/browse/WW">Issue Tracker</a></li>
<li><a href="/security.html">Reporting Security Issues</a></li>
<li><a href="/commercial-support.html">Commercial Support</a></li>
<li class="divider"></li>
<li><a href="https://cwiki.apache.org/confluence/display/WW/Migration+Guide">Version Notes</a></li>
<li><a href="https://cwiki.apache.org/confluence/display/WW/Security+Bulletins">Security Bulletins</a></li>
<li class="divider"></li>
<li><a href="/maven/project-info.html">Maven Project Info</a></li>
<li><a href="/maven/struts2-core/dependencies.html">Struts Core Dependencies</a></li>
<li><a href="/maven/struts2-plugins/modules.html">Plugin Dependencies</a></li>
</ul>
</li>
<li class="dropdown">
<a data-toggle="dropdown" href="#" class="dropdown-toggle">
Documentation<b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li><a href="/birdseye.html">Birds Eye</a></li>
<li><a href="/primer.html">Key Technologies</a></li>
<li><a href="/kickstart.html">Kickstart FAQ</a></li>
<li><a href="https://cwiki.apache.org/confluence/display/WW/Home">Wiki</a></li>
<li class="divider"></li>
<li><a href="/getting-started/">Getting Started</a></li>
<li><a href="/security/">Security Guide</a></li>
<li><a href="/core-developers/">Core Developers Guide</a></li>
<li><a href="/tag-developers/">Tag Developers Guide</a></li>
<li><a href="/maven-archetypes/">Maven Archetypes</a></li>
<li><a href="/plugins/">Plugins</a></li>
<li><a href="/maven/struts2-core/apidocs/index.html">Struts Core API</a></li>
<li><a href="/tag-developers/tag-reference.html">Tag reference</a></li>
<li><a href="https://cwiki.apache.org/confluence/display/WW/FAQs">FAQs</a></li>
<li><a href="http://cwiki.apache.org/S2PLUGINS/home.html">Plugin registry</a></li>
</ul>
</li>
<li class="dropdown">
<a data-toggle="dropdown" href="#" class="dropdown-toggle">
Contributing<b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li><a href="/youatstruts.html">You at Struts</a></li>
<li><a href="/helping.html">How to Help FAQ</a></li>
<li><a href="/dev-mail.html">Development Lists</a></li>
<li class="divider"></li>
<li><a href="/submitting-patches.html">Submitting patches</a></li>
<li><a href="/builds.html">Source Code and Builds</a></li>
<li><a href="/coding-standards.html">Coding standards</a></li>
<li><a href="/contributors/">Contributors Guide</a></li>
<li class="divider"></li>
<li><a href="/release-guidelines.html">Release Guidelines</a></li>
<li><a href="/bylaws.html">PMC Charter</a></li>
<li><a href="/volunteers.html">Volunteers</a></li>
<li><a href="https://gitbox.apache.org/repos/asf?p=struts.git">Source Repository</a></li>
<li><a href="/updating-website.html">Updating the website</a></li>
</ul>
</li>
<li class="apache"><a href="http://www.apache.org/"><img src="/img/apache.png"></a></li>
</ul>
</div>
</div>
</div>
</nav>
</header>
<article class="container">
<section class="col-md-12">
<a class="edit-on-gh" href="https://github.com/apache/struts-site/edit/master/source/getting-started/form-validation-using-xml.md" title="Edit this page on GitHub">Edit on GitHub</a>
<a href="index.html" title="back to Getting started"><< back to Getting started</a>
<h1 class="no_toc" id="form-validation-using-xml">Form Validation Using XML</h1>
<ul id="markdown-toc">
<li><a href="#introduction" id="markdown-toc-introduction">Introduction</a></li>
<li><a href="#example-application" id="markdown-toc-example-application">Example Application</a></li>
<li><a href="#validation-using-xml" id="markdown-toc-validation-using-xml">Validation Using XML</a></li>
<li><a href="#xml-validator-format" id="markdown-toc-xml-validator-format">XML Validator Format</a></li>
<li><a href="#validating-an-email-address" id="markdown-toc-validating-an-email-address">Validating An Email Address</a></li>
<li><a href="#validating-a-users-input-using-a-regular-expression" id="markdown-toc-validating-a-users-input-using-a-regular-expression">Validating A User’s Input Using A Regular Expression</a></li>
<li><a href="#validating-a-users-input-using-an-ognl-expression" id="markdown-toc-validating-a-users-input-using-an-ognl-expression">Validating A User’s Input Using An OGNL Expression</a></li>
<li><a href="#summary" id="markdown-toc-summary">Summary</a></li>
</ul>
<p>The example code for this tutorial, <strong>form-xml-validation</strong>, is available for checkout at <a href="https://github.com/apache/struts-examples">struts-examples</a></p>
<h2 id="introduction">Introduction</h2>
<p>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 <a href="form-validation">Form Validation</a> 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.</p>
<p>The <a href="http://struts.apache.org/mail">Struts 2 user mailing list</a> is an excellent place to get help. If you are having
a problem getting the tutorial example applications to work search the Struts 2 mailing list. If you don’t find an answer
to your problem, post a question on the mailing list.</p>
<h2 id="example-application">Example Application</h2>
<p>The example application that supports this tutorial shows how to use Struts 2’s XML validation methodology.
The information that can be edited is encapsulated in an object of class Person.</p>
<p>To enable the user to edit his information that is stored in the Person object, we have this form:</p>
<p><img src="attachments/att20873263_form-validation-1.png" alt="form-validation-1.png" /></p>
<p>When the user submits the form, we want to validate his entries into the form fields.</p>
<h2 id="validation-using-xml">Validation Using XML</h2>
<p>To validate a user’s form field entries you can use a separate XML file that contains your validation rules.
The XML file that contains the validation rules must be named as ActionClassName-validation.xml. In the example
application, the XML validation file is named EditAction-validation.xml (see src/main/resources/org/apache/struts/edit/action).</p>
<p>Struts 2 provides several different validators that you can use in the XML validation file. See <a href="../core-developers/validation">Validation</a>
for a list of validators you can employ.</p>
<p>In the above form, we want to ensure the user enters a first name. To have the Struts 2 framework enforce that rule
we can use the Struts 2 <a href="../core-developers/requiredstring-validator">requiredstring validator</a>. This validator checks
that the user has entered a string value in the form field.</p>
<h2 id="xml-validator-format">XML Validator Format</h2>
<p>In the XML validation file (for this example that is EditAction-validation.xml), is this XML:</p>
<p><strong>XML Validator Required String</strong></p>
<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">&lt;!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.3//EN" "http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd"&gt;</span>
<span class="nt">&lt;validators&gt;</span>
<span class="nt">&lt;validator</span> <span class="na">type=</span><span class="s">"requiredstring"</span><span class="nt">&gt;</span>
<span class="nt">&lt;param</span> <span class="na">name=</span><span class="s">"fieldname"</span><span class="nt">&gt;</span>personBean.firstName<span class="nt">&lt;/param&gt;</span>
<span class="nt">&lt;message&gt;</span>First name is required.<span class="nt">&lt;/message&gt;</span>
<span class="nt">&lt;/validator&gt;</span>
<span class="nt">&lt;/validators&gt;</span>
</code></pre></div></div>
<p>Within the validators node you can have 1 or more validator nodes. The type attribute specifies which validator you
want the Struts 2 framework to use (see <a href="../core-developers/validation">Validation</a> ). The param name=”fieldname” node
is used to tell the framework which form field entry to apply the rule to. See edit.jsp for the form fields and their
name value (review <a href="form-tags">Struts 2 Form Tags</a> if you’re not familiar with how to use Struts 2 form tags). T
he message node is used to tell the framework what message to display if the validation fails.</p>
<p>| There are alternate ways to write the XML that goes in the validation XML file. See <a href="../core-developers/validation">Validation</a>
in the Struts 2 documentation for a full discussion.</p>
<p>For example if the user doesn’t enter a value in the first name form field and clicks on the Save Changes button, h
e will see the following.</p>
<p><img src="attachments/att20873264_form-validation-2.png" alt="form-validation-2.png" /></p>
<h2 id="validating-an-email-address">Validating An Email Address</h2>
<p>You can use the Struts 2 <a href="../core-developers/email-validator">email validator</a> to validate the user’s input in the email
field. Here is the validator node that is in the <code class="language-plaintext highlighter-rouge">EditAction-validation.xml</code> file.</p>
<p><strong>Email Validator</strong></p>
<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt">&lt;validator</span> <span class="na">type=</span><span class="s">"requiredstring"</span><span class="nt">&gt;</span>
<span class="nt">&lt;param</span> <span class="na">name=</span><span class="s">"fieldname"</span><span class="nt">&gt;</span>personBean.email<span class="nt">&lt;/param&gt;</span>
<span class="nt">&lt;message&gt;</span>Email address is required.<span class="nt">&lt;/message&gt;</span>
<span class="nt">&lt;/validator&gt;</span>
<span class="nt">&lt;validator</span> <span class="na">type=</span><span class="s">"email"</span><span class="nt">&gt;</span>
<span class="nt">&lt;param</span> <span class="na">name=</span><span class="s">"fieldname"</span><span class="nt">&gt;</span>personBean.email<span class="nt">&lt;/param&gt;</span>
<span class="nt">&lt;message&gt;</span>Email address not valid.<span class="nt">&lt;/message&gt;</span>
<span class="nt">&lt;/validator&gt;</span>
</code></pre></div></div>
<p>Note that in the example, we are requiring the user to enter an email address and then validating the email address the user entered.</p>
<h2 id="validating-a-users-input-using-a-regular-expression">Validating A User’s Input Using A Regular Expression</h2>
<p>The Struts 2 framework provides a powerful way to validate a user’s form field input by using the <a href="../core-developers/regex-validator">regex validator</a>.
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 <a href="../core-developers/regex-validator">regex validator</a> to enforce this rule.</p>
<p><strong>REGEX Validator</strong></p>
<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt">&lt;validator</span> <span class="na">type=</span><span class="s">"requiredstring"</span><span class="nt">&gt;</span>
<span class="nt">&lt;param</span> <span class="na">name=</span><span class="s">"fieldname"</span><span class="nt">&gt;</span>personBean.phoneNumber<span class="nt">&lt;/param&gt;</span>
<span class="nt">&lt;message&gt;</span>Phone number is required.<span class="nt">&lt;/message&gt;</span>
<span class="nt">&lt;/validator&gt;</span>
<span class="nt">&lt;validator</span> <span class="na">type=</span><span class="s">"regex"</span><span class="nt">&gt;</span>
<span class="nt">&lt;param</span> <span class="na">name=</span><span class="s">"fieldname"</span><span class="nt">&gt;</span>personBean.phoneNumber<span class="nt">&lt;/param&gt;</span>
<span class="nt">&lt;param</span> <span class="na">name=</span><span class="s">"regex"</span><span class="nt">&gt;</span><span class="cp">&lt;![CDATA[\d{3}-\d{3}-\d{4}]]&gt;</span><span class="nt">&lt;/param&gt;</span>
<span class="nt">&lt;message&gt;</span>Phone number must be entered as 999-999-9999.<span class="nt">&lt;/message&gt;</span>
<span class="nt">&lt;/validator&gt;</span>
</code></pre></div></div>
<p>The <code class="language-plaintext highlighter-rouge">param name="regex"</code> node is used to specify the regular expression that will be applied to the user’s input.
Note how the regular expression is contained within a CDATA section.</p>
<h2 id="validating-a-users-input-using-an-ognl-expression">Validating A User’s Input Using An OGNL Expression</h2>
<p>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 <a href="../core-developers/fieldexpression-validator">fieldexpression validator</a>.
Here’s the XML for that validator node.</p>
<p><strong>FieldExpression Validator</strong></p>
<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt">&lt;validator</span> <span class="na">type=</span><span class="s">"fieldexpression"</span><span class="nt">&gt;</span>
<span class="nt">&lt;param</span> <span class="na">name=</span><span class="s">"fieldname"</span><span class="nt">&gt;</span>personBean.carModels<span class="nt">&lt;/param&gt;</span>
<span class="nt">&lt;param</span> <span class="na">name=</span><span class="s">"expression"</span><span class="nt">&gt;</span><span class="cp">&lt;![CDATA[personBean.carModels.length &gt; 0]]&gt;</span><span class="nt">&lt;/param&gt;</span>
<span class="nt">&lt;message&gt;</span>You must select at least one car model.<span class="nt">&lt;/message&gt;</span>
<span class="nt">&lt;/validator&gt;</span>
</code></pre></div></div>
<p>The param name=”expression” node contains an OGNL expression that evaluates to true or false. We haven’t previously
discussed OGNL, which stands for Object-Graph Navigation Language (see <a href="https://github.com/jkuhnert/ognl">https://github.com/jkuhnert/ognl</a>
and <a href="../tag-developers/ognl">OGNL</a> ). OGNL expressions can be evaluated by the Struts 2 framework as Java statements.</p>
<p>In the above XML the value of the param name=”expression” node, personBean.carModels.length &gt; 0, will be evaluated
by the framework as a Java statement. The part personBean.carModels tells the framework to call the getCarModels
method of class Person. That method returns an Array. Since class Array has a length attribute, the framework will get
the value of the length attribute of the Array returned by the getCarModels method.</p>
<p>If the user did not check any of the check boxes, the Array returned by the getCarModels method will have a length
value of 0. Since the complete OGNL expression will only evaluate to true if the length value is greater than 0,
the validation fails. The user will see this.</p>
<p><img src="attachments/att20873265_form-validation-3.png" alt="form-validation-3.png" /></p>
<p>The fieldexpression validator is useful when doing conditional validation of a user’s input. If the OGNL expression
doesn’t evaluate to true then the user’s input won’t be allowed.</p>
<h2 id="summary">Summary</h2>
<p>The Struts 2 framework provides easy-to-use validation methodologies. You can add a validate method to the Action class
or have a separate XML file with validation rules or you can use a combination of both methodologies.</p>
<table>
<tbody>
<tr>
<td>Return to <a href="form-tags">Form tags</a></td>
<td>or</td>
<td>onward to <a href="control-tags">Control tags</a></td>
</tr>
</tbody>
</table>
</section>
</article>
<footer class="container">
<div class="col-md-12">
Copyright &copy; 2000-2022 <a href="https://www.apache.org/">The Apache Software Foundation</a>.
Apache Struts, Struts, Apache, the Apache feather logo, and the Apache Struts project logos are
trademarks of The Apache Software Foundation. All Rights Reserved.
</div>
<div class="col-md-12">Logo and website design donated by <a href="https://softwaremill.com/">SoftwareMill</a>.</div>
</footer>
<script>!function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (!d.getElementById(id)) {
js = d.createElement(s);
js.id = id;
js.src = "//platform.twitter.com/widgets.js";
fjs.parentNode.insertBefore(js, fjs);
}
}(document, "script", "twitter-wjs");</script>
<script src="https://apis.google.com/js/platform.js" async="async" defer="defer"></script>
<div id="fb-root"></div>
<script>(function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s);
js.id = id;
js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
</body>
</html>