Sophie

Sophie

distrib > CentOS > 5 > x86_64 > by-pkgid > 2607af3e7d36bc31daab2a608fe734e0 > files > 81

struts-manual-1.2.9-4jpp.8.el5_10.x86_64.rpm

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>The Struts User's Guide - Validator Guide</title>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<meta content="David Winterfeldt" name="author" />
<meta content="James Turner" name="author" />
<meta content="Rob Leland" name="author" />
<meta content="Niall Pemberton" name="author" />
<link href="../struts.css" type="text/css" rel="stylesheet" />
</head>
<body>
<div id="heading">
<a href="http://apache.org/">
<img id="asf_logo_wide" alt="The Apache Project" src="../images/asf_logo_wide.gif" />
</a>
<a href="http://struts.apache.org/">
<img id="struts-logo" alt="Struts Framework" src="../images/struts.gif" />
</a>
</div>
<!--end heading-->
<div id="content">
<div id="menu">

    
    
    <p>User Guide</p>
<ul>
      <li>
<a href="index.html">Table of Contents</a>
</li>
      <li>
<a href="preface.html">Preface</a>
</li>
      <li>
<a href="introduction.html">Introduction</a>
</li>
      <li>
<a href="building_model.html">Model Components</a>
</li>
      <li>
<a href="building_view.html">View Components</a>
</li>
      <li>
<a href="building_controller.html">Controller Components</a>
</li>
      <li>
<a href="configuration.html">Configuration</a>
</li>
      <li>
<a href="release-notes.html">Release Notes</a>
</li>
      <li>
<a href="installation.html">Installation</a>
</li>
    </ul>

    <p>Developer Guides</p>
<ul>
        <li>
<a href="dev_bean.html">Bean Tags</a>
</li>
        <li>
<a href="dev_html.html">HTML Tags</a>
</li>
        <li>
<a href="dev_logic.html">Logic Tags</a>
</li>
        <li>
<a href="dev_nested.html">Nested Tags</a>
</li>
        <li>
<a href="dev_tiles.html">Tiles Tags</a>
</li>
        <li>
<a href="dev_util.html">Utilities</a>
</li>
        <li>
<a href="dev_validator.html">Validator</a>
</li>
    </ul>

    <p>Quick Links</p>
<ul>
        <li>
<a href="../index.html">Welcome</a>
</li>
        <li>
<a href="index.html">User and Developer Guides *</a>
</li>
        <li>
<a href="../faqs/index.html">FAQs and HowTos</a>
</li>
    </ul>

<div class="authors">
<p>
<strong>Contributors</strong>
</p>
<ul>
<li>David Winterfeldt</li>
<li>James Turner</li>
<li>Rob Leland</li>
<li>Niall Pemberton</li>
</ul>
</div>
</div>
<!--end menu-->
<div id="main">

<h1>Struts Validator Guide</h1>
<h2 id="validator">Struts Validator</h2>
<div class="indent">

    <p>
    The Struts Validator, in some form, has been available since the
    days of Struts 0.5.
    It was orignally packaged as a developer contribution.
    Later, the core code was moved to the Jakarta Commons and
    a Struts specific extension became part of Struts since 1.1.
    </p>

    <p>
    For the convenience of the many developers who have been using
    the Struts Validator all along, this document first overviews
    the core functionality and then covers the changes and
    new functionality added since Struts 1.1.
    </p>

    <p>
    Once you have configured the Validator Plug-In, so that it can load your
    Validator Resources you just have to extend
    <code>org.apache.struts.validator.action.ValidatorForm</code> instead of
    <code>org.apache.struts.action.ActionForm</code>.
    Then when the <code>validate</code> method is called, the action's name
    attribute from the Struts Configuration is used to load the validations for
    the current form.
    The form element's <code>name</code> attribute in the
    Validator configuration should match the action element's <code>name</code>
    attribute.
    </p>

    <p>
    An alternative approach is to use the action mapping path attribute.
    In this case, you extend the ValidatorActionForm instead of the ValidatorForm.
    The ValidatorActionForm uses the action element's <code>path</code>
    attribute from the Struts configuration which should match the form element's
    <code>name</code> attribute in the Validator configuration.
    </p>

    <p>
    Then a separate action mapping can be defined for each page in a multi-page
    form, and the validation form can be associated with the action rather than
    a page number (as shown in the example of a multi-page form in the validator
    example).
    </p>

</div>
<h2 id="i18n">Internationalization</h2>
<div class="indent">

    <p>
    Each validator form is grouped within a <code>FormSet</code> element in
    the Validator configuration file.
    The <code>FormSet</code> has language, country, and variant attributes that
    correspond with the <code>java.util.Locale</code> class.
    If these attributes are not specified, the <code>FormSet</code> will be set
    to the default locale.
    A <code>FormSet</code> can also have constants associated with it.
    On the same level as a <code>FormSet</code> there can be a global element
    which can also have constants and have validator actions that perform
    validations.
    </p>
    <p>
    <strong>Note</strong>: You must declare a default <code>FormSet</code> without 
    internationalization before your internationalized <code>FormSet</code>s.  This
    allows the Validator to fall back to the default version if no locale is found.
    </p>

    <p>
    The default error message for a pluggable validator can be overriden with
    the <code>msg</code> element.
    So instead of using the <code>msg</code> attribute for the mask validator
    to generate the error message the <code>msg</code> attribute from the
    field will be used if the name of the field's name attribute matches the
    validator's name attribute.
    </p>

    <p>
    The arguments for error messages can be set with the arg0-arg3 elements.
    If the arg0-arg3 elements' name attribute isn't set, it will become the
    default arg value for the different error messages constructed.
    If the name attribute is set, you can specify the argument for a specific
    pluggable validator and then this will be used for constructing the error
    message.
    </p>

<pre>
<code>
&lt;field
    property="lastName"
    depends="required,mask"&gt;
    &lt;msg
        name="mask"
        key="registrationForm.lastname.maskmsg"/&gt;
    &lt;arg0 key="registrationForm.lastname.displayname"/&gt;
    &lt;var&gt;
        &lt;var-name&gt;mask&lt;/var-name&gt;
        &lt;var-value&gt;^[a-zA-Z]*$&lt;/var-value&gt;
    &lt;/var&gt;
&lt;/field&gt;
</code>
</pre>

    <p>
    By default the arg0-arg3 elements will try to look up the <code>key</code>
    attribute in the message resources.
    If the resource attribute is set to false, it will pass in the value directly
    without retrieving the value from the message resources.
    </p>
    <p>
    Note that since Struts 1.1, you must explicitly define your message
    resource in any module that is going to use the Validator, due to a problem
    accessing the top-level resource.  This only effects applications which are
    using modules.
    </p>

<pre>
<code>
&lt;field
    property="integer"
    depends="required,integer,intRange"&gt;
    &lt;arg0 key="typeForm.integer.displayname"/&gt;
    &lt;arg1
        name="intRange"
        key="${var:min}"
        resource="false"/&gt;
    &lt;arg2
        name="intRange"
        key="${var:max}"
        resource="false"/&gt;
    &lt;var&gt;
        &lt;var-name&gt;min&lt;/var-name&gt;
        &lt;var-value&gt;10&lt;/var-value&gt;
    &lt;/var&gt;
    &lt;var&gt;
        &lt;var-name&gt;max&lt;/var-name&gt;
        &lt;var-value&gt;20&lt;/var-value&gt;
    &lt;/var&gt;
    &lt;/field&gt;
</code>
</pre>

</div>
<h2 id="builtin">Standard Built In Validations</h2>
<div class="indent">

        <p>
        Validator ships with a set of pre-defined validators, as follows:
        </p>
            <ul>
              <li>
<strong>required</strong> - mandatory field validation. Has no variables.
    <pre>
<code>
    &lt;field property="name" depends="required"&gt;
        &lt;arg0 key="customer.name"/&gt;
    &lt;/field&gt;
    </code>
</pre>
              </li>
              <li>
<strong>requiredif</strong> - field dependant validator
                  <pre>Deprecated, use validwhen.</pre>
              </li>
              <li>
<strong>validwhen</strong> - validator for checking one field against another.
                  <pre>see later section titled <strong>Designing "Complex Validations with validwhen"</strong>.</pre>
              </li>
              <li>
<strong>minlength</strong> - validate input data isn't less than a specified minimum length.
                  Requires a <code>minlength</code> variable.
    <pre>
<code>
    &lt;field property="name" depends="required,minlength"&gt;
        &lt;arg0 key="customer.name"/&gt;
        &lt;arg1 name="minlength" key="${var:minlength}" resource="false"/&gt;
        &lt;var&gt;&lt;var-name&gt;minlength&lt;/var-name&gt;&lt;var-value&gt;3&lt;/var-value&gt;&lt;/var&gt;
    &lt;/field&gt;
    </code>
</pre>
              </li>
              <li>
<strong>maxlength</strong> - validate input data doesn't exceed a specified maximum length.
                  Requires a <code>maxlength</code> variable.
    <pre>
<code>
    &lt;field property="name" depends="required,maxlength"&gt;
        &lt;arg0 key="customer.name"/&gt;
        &lt;arg1 name="maxlength" key="${var:maxlength}" resource="false"/&gt;
        &lt;var&gt;&lt;var-name&gt;maxlength&lt;/var-name&gt;&lt;var-value&gt;30&lt;/var-value&gt;&lt;/var&gt;
    &lt;/field&gt;
    </code>
</pre>
              </li>
              <li>
<strong>mask</strong> - validate format according to a regular expression.
                  Requires a <code>mask</code> variable to specify the regular expression.
                  Since version 1.1, the regular expression must start
                  with a <code>^</code> and end with a <code>$</code> (see example below).
    <pre>
<code>
    &lt;field property="name" depends="required,mask"&gt;
        &lt;msg name="mask" key="registrationForm.lastname.maskmsg"/&gt;
        &lt;arg0 key="registration.name"/&gt;
        &lt;var&gt;&lt;var-name&gt;mask&lt;/var-name&gt;&lt;var-value&gt;^[a-zA-Z]*$&lt;/var-value&gt;&lt;/var&gt;
    &lt;/field&gt;
    </code>
</pre>
              </li>
              <li>
<strong>byte</strong> - validates that a field can be converted to a Byte.
    <pre>
<code>
    &lt;field property="age" depends="byte"&gt;
        &lt;arg0 key="employee.age"/&gt;
    &lt;/field&gt;
    </code>
</pre>
              </li>
              <li>
<strong>short</strong> - validates that a field can be converted to a Short.
    <pre>
<code>
    &lt;field property="productnumber" depends="short"&gt;
        &lt;arg0 key="order.prodno"/&gt;
    &lt;/field&gt;
    </code>
</pre>
              </li>
              <li>
<strong>integer</strong> - validates that a field can be converted to an Integer.
    <pre>
<code>
    &lt;field property="ordernumber" depends="integer"&gt;
        &lt;arg0 key="order.number"/&gt;
    &lt;/field&gt;
    </code>
</pre>
              </li>
              <li>
<strong>long</strong> - validates that a field can be converted to a Long.
    <pre>
<code>
    &lt;field property="ordernumber" depends="long"&gt;
        &lt;arg0 key="order.number"/&gt;
    &lt;/field&gt;
    </code>
</pre>
              </li>
              <li>
<strong>float</strong> - validates that a field can be converted to a Float.
    <pre>
<code>
    &lt;field property="amount" depends="float"&gt;
        &lt;arg0 key="sale.amount"/&gt;
    &lt;/field&gt;
    </code>
</pre>
              </li>
              <li>
<strong>double</strong> - validates that a field can be converted to a Double.
    <pre>
<code>
    &lt;field property="amount" depends="double"&gt;
        &lt;arg0 key="sale.amount"/&gt;
    &lt;/field&gt;
    </code>
</pre>
              </li>
              <li>
<strong>date</strong> - validates that a field can be converted to a Date.
                  This validator uses <code>java.text.SimpleDateFormat</code> to parse the date and
                  optionally either a <code>datePattern</code> or <code>datePatternStrict</code> variable can be used.
                  If no pattern is specified the default short date format is assumed. The difference
                  between using the <code>datePatternStrict</code> and <code>datePattern</code> variables
                  is that <code>datePatternStrict</code> checks additionally that the input data is the same
                  length as the pattern specified (so for example 1/1/2004 would fail with a pattern of <code>MM/dd/yyyy</code>).
    <pre>
<code>
    &lt;field property="saledate" depends="required,date"&gt;
        &lt;arg0 key="myForm.saledate"/&gt;
        &lt;var&gt;&lt;var-name&gt;datePattern&lt;/var-name&gt;&lt;var-value&gt;MM/dd/yyyy&lt;/var-value&gt;&lt;/var&gt;
    &lt;/field&gt;
    </code>
</pre>
    <pre>
<code>
    &lt;field property="saledate" depends="required,date"&gt;
        &lt;arg0 key="sale.orderdate"/&gt;
        &lt;var&gt;&lt;var-name&gt;datePatternStrict&lt;/var-name&gt;&lt;var-value&gt;MM/dd/yyyy&lt;/var-value&gt;&lt;/var&gt;
    &lt;/field&gt;
    </code>
</pre>
              </li>
              <li>
<strong>range</strong> - validate number range.
                  <pre>Deprecated, use intRange, floatRange or doubleRange.</pre>
              </li>
              <li>
<strong>intRange</strong> - validates that an integer field is within a specified range.
                  Requires <code>min</code> and <code>max</code> variables to specify the range.
                  This validator depends on the <code>integer</code> validator
                  which must also be in the field's <code>depends</code> attribute.
    <pre>
<code>
    &lt;field property="age" depends="required,integer,intRange"&gt;
        &lt;arg0 key="employee.age"/&gt;
        &lt;arg1 name="intRange" key="${var:min}" resource="false"/&gt;
        &lt;arg2 name="intRange" key="${var:max}" resource="false"/&gt;
        &lt;var&gt;&lt;var-name&gt;min&lt;/var-name&gt;&lt;var-value&gt;18&lt;/var-value&gt;&lt;/var&gt;
        &lt;var&gt;&lt;var-name&gt;max&lt;/var-name&gt;&lt;var-value&gt;65&lt;/var-value&gt;&lt;/var&gt;
    &lt;/field&gt;
    </code>
</pre>
              </li>
              <li>
<strong>floatRange</strong> - validates that a float field is within a specified range
                  Requires <code>min</code> and <code>max</code> variables to specify the range.
                  This validator depends on the <code>float</code> validator
                  which must also be in the field's <code>depends</code> attribute.
    <pre>
<code>
    &lt;field property="ordervalue" depends="required,float,floatRange"&gt;
        &lt;arg0 key="order.value"/&gt;
        &lt;arg1 name="floatRange" key="${var:min}" resource="false"/&gt;
        &lt;arg2 name="floatRange" key="${var:max}" resource="false"/&gt;
        &lt;var&gt;&lt;var-name&gt;min&lt;/var-name&gt;&lt;var-value&gt;100&lt;/var-value&gt;&lt;/var&gt;
        &lt;var&gt;&lt;var-name&gt;max&lt;/var-name&gt;&lt;var-value&gt;4.99&lt;/var-value&gt;&lt;/var&gt;
    &lt;/field&gt;
    </code>
</pre>
              </li>
              <li>
<strong>doubleRange</strong> - validates that a double field is within a specified range
                  Requires <code>min</code> and <code>max</code> variables to specify the range.
                  This validator depends on the <code>double</code> validator
                  which must also be in the field's <code>depends</code> attribute.
    <pre>
<code>
    &lt;field property="ordervalue" depends="required,double,doubleRange"&gt;
        &lt;arg0 key="employee.age"/&gt;
        &lt;arg1 name="doubleRange" key="${var:min}" resource="false"/&gt;
        &lt;arg2 name="doubleRange" key="${var:max}" resource="false"/&gt;
        &lt;var&gt;&lt;var-name&gt;min&lt;/var-name&gt;&lt;var-value&gt;100&lt;/var-value&gt;&lt;/var&gt;
        &lt;var&gt;&lt;var-name&gt;max&lt;/var-name&gt;&lt;var-value&gt;4.99&lt;/var-value&gt;&lt;/var&gt;
    &lt;/field&gt;
    </code>
</pre>
              </li>
              <li>
<strong>creditCard</strong> - validate credit card number format
    <pre>
<code>
    &lt;field property="name" depends="required, creditCard"&gt;
        &lt;arg0 key="customer.cardnumber"/&gt;
    &lt;/field&gt;
    </code>
</pre>
              </li>
              <li>
<strong>email</strong> - validate email address format
    <pre>
<code>
    &lt;field property="customeremail" depends="email"&gt;
        &lt;arg0 key="customer.email"/&gt;
    &lt;/field&gt;
    </code>
</pre>
              </li>
              <li>
<strong>url</strong> - validates url format.
                  Has four <i>optional</i> variables (<code>allowallschemes</code>,
                  <code>allow2slashes</code>, <code>nofragments</code> and <code>schemes</code>)
                  which can be used to configure this validator.
                  <ul>
                    <li>
<strong>allowallschemes</strong> specifies whether all schemes are allowed. Valid
                        values are <code>true</code> or <code>false</code> (default is <code>false</code>).
                        If this is set to <code>true</code> then the <code>schemes</code> variable is ignored.</li>
                    <li>
<strong>allow2slashes</strong> specifies whether double '/' characters are allowed. Valid
                        values are <code>true</code> or <code>false</code> (default is <code>false</code>).</li>
                    <li>
<strong>nofragments</strong> specifies whether fragements are allowed. Valid
                        values are <code>true</code> or <code>false</code> (default is <code>false</code> - i.e. 
                        fragments are allowed).</li>
                    <li>
<strong>schemes</strong> - use to specify a comma separated list of valid schemes. If
                        not specified then the defaults are used which are <code>http</code>, 
                        <code>https</code> and <code>ftp</code>.</li>
                  </ul>
    <pre>
<code>
    &lt;field property="custUrl" depends="url"&gt;
        &lt;arg0 key="customer.url"/&gt;
    &lt;/field&gt;

    &lt;field property="custUrl" depends="url"&gt;
        &lt;arg0 key="customer.url"/&gt;
        &lt;var&gt;
           &lt;var-name&gt;nofragments&lt;/var-name&gt;
           &lt;var-value&gt;true&lt;/var-value&gt;
        &lt;/var&gt;
        &lt;var&gt;
           &lt;var-name&gt;schemes&lt;/var-name&gt;
           &lt;var-value&gt;http,https,telnet,file&lt;/var-value&gt;
        &lt;/var&gt;
    &lt;/field&gt;
    </code>
</pre>
              </li>
            </ul>
    </div>
<h2 id="members">Constants/Variables</h2>
<div class="indent">

    <p>
    Global constants can be inside the global tags and FormSet/Locale
    constants can be created in the formset tags.
    Constants are currently only replaced in the Field's property attribute,
    the Field's var element value attribute, the Field's msg element key
    attribute, and Field's arg0-arg3 element's key attribute.
    A Field's variables can also be substituted in the arg0-arg3
    elements (ex: ${var:min}).
    The order of replacement is FormSet/Locale constants are replaced first,
    Global constants second, and for the arg elements variables are replaced
    last.
    </p>

<pre>
<code>
&lt;global&gt;
    &lt;constant&gt;
        &lt;constant-name&gt;zip&lt;/constant-name&gt;
        &lt;constant-value&gt;^\d{5}(-\d{4})?$&lt;/constant-value&gt;
    &lt;/constant&gt;
&lt;/global&gt;

&lt;field
   property="zip"
   depends="required,mask"&gt;
&lt;arg0 key="registrationForm.zippostal.displayname"/&gt;
&lt;var&gt;
 &lt;var-name&gt;mask&lt;/var-name&gt;
 &lt;var-value&gt;${zip}&lt;/var-value&gt;
&lt;/var&gt;
&lt;/field&gt;
</code>
</pre>

    <p>
    The var element under a field can be used to store variables for use by a
    pluggable validator.
    These variables are available through the Field's
    <code>getVar(String key)</code> method.
    </p>

<pre>
<code>
&lt;field
    property="integer"
    depends="required,integer,intRange"&gt;
    &lt;arg0 key="typeForm.integer.displayname"/&gt;
    &lt;arg1
        name="intRange"
        key="${var:min}"
        resource="false"/&gt;
    &lt;arg2
        name="intRange"
        key="${var:max}"
        resource="false"/&gt;
    &lt;var&gt;
        &lt;var-name&gt;min&lt;/var-name&gt;
        &lt;var-value&gt;10&lt;/var-value&gt;
    &lt;/var&gt;
    &lt;var&gt;
        &lt;var-name&gt;max&lt;/var-name&gt;
        &lt;var-value&gt;20&lt;/var-value&gt;
    &lt;/var&gt;
    &lt;/field&gt;
</code>
</pre>

</div>
<h2 id="validwhen">Designing Complex Validations with validwhen</h2>
<div class="indent">
    <p>
    [Since Struts 1.2.0] A frequent requirement in validation design is to validate one field
    against another (for example, if you have asked the user to type in
    a password twice for confirmation, to make sure that the values match.)
    In addition, there are fields in a form that may only be required if
    other fields have certain values.  The <code>validwhen</code>
    validator is designed to handle these cases.</p>
    <p>
    The <code>validwhen</code> validator takes a single <code>var</code> field,
    called <code>test</code>.  The value of this var is a boolean expression
    which must be true in order for the validation to success.  The
    values which are allowed in the expression are:</p>
    <ul>
      <li>Single or double-quoted string literals.</li>
      <li>Integer literals in decimal, hex or octal format</li>
      <li>The value <code>null</code> which will match against either
      null or an empty string</li>
      <li>Other fields in the form referenced by field name, such as
      <code>customerAge</code>
</li>
      <li>Indexed fields in the form referenced by an explicit integer, 
      such as <code>childLastName[2]</code>
</li>
      <li>Indexed fields in the form referenced by an implicit integer, 
      such as <code>childLastName[]</code>, which will use the same
      index into the array as the index of the field being tested.</li>
      <li>Properties of an indexed fields in the form referenced by an 
      explicit or implicit integer, such as <code>child[].lastName</code>, 
      which will use the same index into the array as the index of the 
      field being tested.</li>
      <li>The literal <code>*this*</code>, which contains the value of
      the field currently being tested</li>
   </ul>
   <p>
      As an example of how this would work, consider a form with
      fields <code>sendNewsletter</code> and <code>emailAddress</code>.
      The <code>emailAddress</code> field is only required if the
      <code>sendNewsletter</code> field is not null.  You could code
      this using validwhen as:</p>
<pre>
<code>
&lt;field property="emailAddress" depends="validwhen"&gt;
      &lt;arg0 key="userinfo.emailAddress.label"/&gt;
        &lt;var&gt;
          &lt;var-name&gt;test&lt;/var-name&gt;
          &lt;var-value&gt;((sendNewsletter == null) or (*this* != null))&lt;/var-value&gt;
        &lt;/var&gt;
      &lt;/field&gt;
</code>
</pre>
<p>
      Which reads as: this field is valid if <code>sendNewsletter</code> is 
      <code>null</code> or the field value is not <code>null</code>.</p>
<p>
      Here's a slightly more complicated example using indexed fields.
      Assume a form with a number of lines to allow the user to enter
      part numbers and quantities they wish to order.  An array of
      beans of class <code>orderLine</code> is used to hold the entries in
      a property called orderLines.
      If you wished to verify that every line with part number also had
      a quantity entered, you could do it with:</p>
<pre>
<code>
    &lt;field property="quantity" indexedListProperty="orderLines" depends="validwhen"&gt;
      &lt;arg0 key="orderform.quantity.label"/&gt;
        &lt;var&gt;
          &lt;var-name&gt;test&lt;/var-name&gt;
          &lt;var-value&gt;((orderLines[].partNumber == null) or (*this* != null))&lt;/var-value&gt;
        &lt;/var&gt;
      &lt;/field&gt;
</code>
</pre>
     <p>
     Which reads as: This field is value if the corresponding <code>partNumber
     </code> field is <code>null</code>, or this field is not <code>null</code>.
     </p>
     <p>
     As a final example, imagine a form where the user must enter their
     height in inches, and if they are under 60 inches in height, it is
     an error to have checked off nbaPointGuard as a career.</p>
<pre>
<code>
    &lt;field property="nbaPointGuard" depends="validwhen"&gt;
      &lt;arg0 key="careers.nbaPointGuard.label"/&gt;
        &lt;var&gt;
          &lt;var-name&gt;test&lt;/var-name&gt;
          &lt;var-value&gt;((heightInInches &gt;= 60) or (*this* == null))&lt;/var-value&gt;
        &lt;/var&gt;
      &lt;/field&gt;
</code>
</pre>
     <p>
     A few quick notes on the grammer.</p>
     <ul>
       <li>All comparisons must be enclosed in parens.</li>
       <li>Only two items may be joined with <code>and</code> or <code>or</code>
</li>
       <li>If both items to be compared are convertable to ints, a numeric
       comparison is done, otherwise a string comparison is done.
       </li>
     </ul>
</div>
<h2 id="plugs">Pluggable Validators</h2>
<div class="indent">

    <p>
    By convention, the validators your application uses can beloaded through a
    file named "validator-rules.xml", and the validator forms (or "validations")
    can be configured separately (say, in a "validations.xml" file). This
    approach separates the validators, that you might reuse in another
    application, from the validations that are specific to each application.
    </p>

    <p>
    The Validator comes bundled with several ready-to-use validators. The
    bundled validators include: required, mask ,byte, short, int, long,
    float, double, date (without locale support), and a numeric range.
    </p>

    <p>
    The 'mask' validator depends on 'required' in the default setup.
    That means that 'required' has to complete successfully before 'mask' will
    run.
    The 'required' and 'mask' validators are partially built into the framework.
    Any field that isn't 'required' will skip other validations if the field is null
    or has a length of zero. Regardless, the implementations of 'required' and 'mask'
    are still plugged in through the configuration file, like all the others.
    </p>

    <p>
    If the <a href="struts-html.html#javascript">Javascript Tag</a> is used,
    the client side Javascript generation looks for a value in the validator's
    javascript attribute and generates an object that the supplied method can
    use to validate the form.
    For a more detailed explanation of how the Javascript Validator Tag works,
    see the <a href="struts-html.html">html taglib API reference</a>.
    </p>

    <p>
    The 'mask' validator lets you validate a regular expression mask to the field.
    It uses the Regular Expression Package from the Apache Jakarta site.
    </p>

    <p>
    The main class used is <code>org.apache.regexp.RE</code>.
    </p>

    <p>
    Example Validator Configuration from the default validator-rules.xml.
    </p>

<pre>
<code>
&lt;validator name="required"
        classname="org.apache.struts.validator.FieldChecks"
        method="validateRequired"
        methodParams="java.lang.Object,
                 org.apache.commons.validator.ValidatorAction,
                 org.apache.commons.validator.Field,
                 org.apache.struts.action.ActionErrors,
                 javax.servlet.http.HttpServletRequest"
        msg="errors.required"&gt;

&lt;validator name="mask"
        classname="org.apache.struts.validator.FieldChecks"
        method="validateMask"
        methodParams="java.lang.Object,
                 org.apache.commons.validator.ValidatorAction,
                 org.apache.commons.validator.Field,
                 org.apache.struts.action.ActionErrors,
                 javax.servlet.http.HttpServletRequest"
        msg="errors.invalid"&gt;
</code>
</pre>

    <p>
    <strong>Creating Pluggable Validators</strong>
    </p>

    <p>
    The <code>methodParams</code> attribute takes a comma separated list
    of class names. The <code>method</code> attribute needs to have a signature
    complying with the above list. The list can be comprised of any combination
    of the following:
    </p>

    <ul>

        <li>
        <code>java.lang.Object</code>
        - Bean validation is being performed on.
        </li>

        <li>
        <code>org.apache.commons.validator.ValidatorAction</code>
        - The current ValidatorAction being performed.
        </li>

        <li>
        <code>org.apache.commons.validator.Field</code>
        - Field object being validated.
        </li>

        <li>
        <code>org.apache.struts.action.ActionErrors</code>
        - The errors objects to add an ActionError to if the validation fails.
        </li>

        <li>
        <code>javax.servlet.http.HttpServletRequest</code>
        - Current request object.
        </li>

        <li>
        <code>javax.servlet.ServletContext</code>
        - The application's ServletContext.
        </li>

        <li>
        <code>org.apache.commons.validator.Validator</code>
        - The current org.apache.commons.validator.Validator instance.
        </li>

        <li>
        <code>java.util.Locale</code>
        - The Locale of the current user.
        </li>

    </ul>

    <p>
    <strong>Multi Page Forms</strong>
    </p>

    <p>
    The field element has an optional page attribute.
    It can be set to an integer.
    All validation for any field on a page less than or equal to the
    current page is performed server side.
    All validation for any field on a page equal to the current page is
    generated for the client side Javascript.
    A mutli-part form expects the page attribute to be set.
    </p>

<pre>
<code>
&lt;html:hidden property="page" value="1"/&gt;
</code>
</pre>

    <p>
    <strong>Comparing Two Fields</strong>
    </p>

    <p>
    This is an example of how you could compare two fields to see if they
    have the same value.
    A good example of this is when you are validating a user changing their
    password and there is the main password field and a confirmation field.
    </p>

<pre>
<code>
&lt;validator name="twofields"
       classname="com.mysite.StrutsValidator"
       method="validateTwoFields"
       msg="errors.twofields"/&gt;

&lt;field property="password"
       depends="required,twofields"&gt;
          &lt;arg0 key="typeForm.password.displayname"/&gt;
          &lt;var&gt;
             &lt;var-name&gt;secondProperty&lt;/var-name&gt;
             &lt;var-value&gt;password2&lt;/var-value&gt;
          &lt;/var&gt;
&lt;/field&gt;
</code>
</pre>

<pre>
<code>
public static boolean validateTwoFields(
    Object bean,
    ValidatorAction va, 
    Field field,
    ActionErrors errors,
    HttpServletRequest request, 
    ServletContext application) {

    String value = ValidatorUtils.getValueAsString(
        bean, 
        field.getProperty());
    String sProperty2 = field.getVarValue("secondProperty");
    String value2 = ValidatorUtils.getValueAsString(
        bean, 
        sProperty2);

    if (!GenericValidator.isBlankOrNull(value)) {
       try {
          if (!value.equals(value2)) {
             errors.add(field.getKey(),
                Resources.getActionError(
                    application,
                    request,
                    va,
                    field));

             return false;
          }
       } catch (Exception e) {
             errors.add(field.getKey(),
                Resources.getActionError(
                    application,
                    request,
                    va,
                    field));
             return false;
       }
    }

    return true;
}
</code>
</pre>

</div>
<h2 id="validator-bugs">Known Bugs</h2>
<div class="indent">

    <p>
    Since the Struts Validator relies on the Commons Validator, problem
    reports and enhancement requests may be listed against either product.
    </p>

    <ul>

        <li>
        <a href="http://nagoya.apache.org/bugzilla/buglist.cgi?bug_status=UNCONFIRMED&amp;bug_status=NEW&amp;bug_status=ASSIGNED&amp;bug_status=REOPENED&amp;bug_status=VERIFIED&amp;bug_severity=Blocker&amp;bug_severity=Critical&amp;bug_severity=Major&amp;bug_severity=Normal&amp;bug_severity=Minor&amp;email1=&amp;emailtype1=substring&amp;emailassigned_to1=1&amp;email2=&amp;emailtype2=substring&amp;emailreporter2=1&amp;bugidtype=include&amp;bug_id=&amp;changedin=&amp;votes=&amp;chfieldfrom=&amp;chfieldto=Now&amp;chfieldvalue=&amp;product=Struts&amp;version=1.1+Beta+1&amp;version=1.1+Beta+2&amp;version=Nightly+Build&amp;version=Unknown&amp;component=Validator+Framework&amp;short_desc=&amp;short_desc_type=allwordssubstr&amp;long_desc=&amp;long_desc_type=allwordssubstr&amp;bug_file_loc=&amp;bug_file_loc_type=allwordssubstr&amp;keywords=&amp;keywords_type=anywords&amp;field0-0-0=noop&amp;type0-0-0=noop&amp;value0-0-0=&amp;cmdtype=doit&amp;order=Bug+Number">
        Struts Validator Bugzilla Reports
        </a>
        </li>

        <li>
        <a href="http://nagoya.apache.org/bugzilla/buglist.cgi?bug_status=UNCONFIRMED&amp;bug_status=NEW&amp;bug_status=ASSIGNED&amp;bug_status=REOPENED&amp;bug_status=VERIFIED&amp;bug_severity=Blocker&amp;bug_severity=Critical&amp;bug_severity=Major&amp;bug_severity=Normal&amp;bug_severity=Minor&amp;email1=&amp;emailtype1=substring&amp;emailassigned_to1=1&amp;email2=&amp;emailtype2=substring&amp;emailreporter2=1&amp;bugidtype=include&amp;bug_id=&amp;changedin=&amp;votes=&amp;chfieldfrom=&amp;chfieldto=Now&amp;chfieldvalue=&amp;product=Commons&amp;component=Validator&amp;short_desc=&amp;short_desc_type=allwordssubstr&amp;long_desc=&amp;long_desc_type=allwordssubstr&amp;bug_file_loc=&amp;bug_file_loc_type=allwordssubstr&amp;keywords=&amp;keywords_type=anywords&amp;field0-0-0=noop&amp;type0-0-0=noop&amp;value0-0-0=&amp;cmdtype=doit&amp;order=Bug+Number">
        Commons Validator Bugzilla Reports</a>
        </li>

    </ul>

</div>
<h2 id="conditionals">Conditionally required fields</h2>
<div class="indent">

    <p>
    You can define logic like "only validate this field if field X is
    non-null and field Y equals 'male'".  The recommended way to do this will
    be with the <code>validwhen</code> validator, described above, and available
    since Struts 1.2.0.  The
    <code>requiredif</code> validator, which was added since Struts 1.1,
    will be deprecated in favor of <code>validwhen</code>, and
    <code>requiredif</code> will be removed in a future release. However, if you
    are using <code>requiredif</code>, here is a brief tutorial.
    </p>

     <p>Let's assume you have a medical information form with three fields, sex, pregnancyTest, and testResult.
     If sex is 'f' or 'F', pregnancyTest is required.  If pregnancyTest is not blank, testResult is required.
     The entry in your Validator configuration would look like this:
     </p>
     <pre>

&lt;form name="medicalStatusForm"&gt;

&lt;field
    property="pregnancyTest" depends="requiredif"&gt;
  &lt;arg0 key="medicalStatusForm.pregnancyTest.label"/&gt;
  &lt;var&gt;
    &lt;var-name&gt;field[0]&lt;/var-name&gt;
    &lt;var-value&gt;sex&lt;/var-value&gt;
  &lt;/var&gt;
  &lt;var&gt;
    &lt;var-name&gt;fieldTest[0]&lt;/var-name&gt;
    &lt;var-value&gt;EQUAL&lt;/var-value&gt;
  &lt;/var&gt;
  &lt;var&gt;
    &lt;var-name&gt;fieldValue[0]&lt;/var-name&gt;
    &lt;var-value&gt;F&lt;/var-value&gt;
  &lt;/var&gt;
  &lt;var&gt;
    &lt;var-name&gt;field[1]&lt;/var-name&gt;
    &lt;var-value&gt;sex&lt;/var-value&gt;
  &lt;/var&gt;
  &lt;var&gt;
    &lt;var-name&gt;fieldTest[1]&lt;/var-name&gt;
    &lt;var-value&gt;EQUAL&lt;/var-value&gt;
  &lt;/var&gt;
  &lt;var&gt;
    &lt;var-name&gt;fieldValue[1]&lt;/var-name&gt;
    &lt;var-value&gt;f&lt;/var-value&gt;
  &lt;/var&gt;
  &lt;var&gt;
    &lt;var-name&gt;fieldJoin&lt;/var-name&gt;
    &lt;var-value&gt;OR&lt;/var-value&gt;
  &lt;/var&gt;
&lt;/field&gt;

&lt;field
    property="testResult" depends="requiredif"&gt;
  &lt;arg0 key="medicalStatusForm.testResult.label"/&gt;
  &lt;var&gt;
    &lt;var-name&gt;field[0]&lt;/var-name&gt;
    &lt;var-value&gt;pregnancyTest&lt;/var-value&gt;
  &lt;/var&gt;
  &lt;var&gt;
    &lt;var-name&gt;fieldTest[0]&lt;/var-name&gt;
    &lt;var-value&gt;NOTNULL&lt;/var-value&gt;
  &lt;/var&gt;
&lt;/field&gt;
&lt;/form&gt;
</pre>

    <p>
    Here's a more complex example using indexed properties.
    </p>

    <p>
    If you have this in your Struts configuration
    </p>

<pre>
&lt;form-bean
    name="dependentlistForm"
    type="org.apache.struts.webapp.validator.forms.ValidatorForm"&gt;
    &lt;form-property
        name="dependents"
        type="org.apache.struts.webapp.validator.Dependent[]" size="10"/&gt;
    &lt;form-property
        name="insureDependents"
        type="java.lang.Boolean"
        initial="false"/&gt;
&lt;/form-bean&gt;
</pre>

    <p>
    Where dependent is a bean that has properties lastName, firstName, dob,
    coverageType
    </p>

    <p>
    You can define a validation:
    </p>

<pre>

&lt;form name="dependentlistForm"&gt;

&lt;field
    property="firstName" indexedListProperty="dependents"
    depends="requiredif"&gt;
  &lt;arg0 key="dependentlistForm.firstName.label"/&gt;
  &lt;var&gt;
    &lt;var-name&gt;field[0]&lt;/var-name&gt;
    &lt;var-value&gt;lastName&lt;/var-value&gt;
  &lt;/var&gt;
  &lt;var&gt;
    &lt;var-name&gt;fieldIndexed[0]&lt;/var-name&gt;
    &lt;var-value&gt;true&lt;/var-value&gt;
  &lt;/var&gt;
  &lt;var&gt;
    &lt;var-name&gt;fieldTest[0]&lt;/var-name&gt;
    &lt;var-value&gt;NOTNULL&lt;/var-value&gt;
  &lt;/var&gt;
&lt;/field&gt;

&lt;field
    property="dob"
    indexedListProperty="dependents"
    depends="requiredif,date"&gt;
  &lt;arg0 key="dependentlistForm.dob.label"/&gt;
  &lt;var&gt;
    &lt;var-name&gt;field[0]&lt;/var-name&gt;
    &lt;var-value&gt;lastName&lt;/var-value&gt;
  &lt;/var&gt;
  &lt;var&gt;
    &lt;var-name&gt;fieldIndexed[0]&lt;/var-name&gt;
    &lt;var-value&gt;true&lt;/var-value&gt;
  &lt;/var&gt;
  &lt;var&gt;
    &lt;var-name&gt;fieldTest[0]&lt;/var-name&gt;
    &lt;var-value&gt;NOTNULL&lt;/var-value&gt;
  &lt;/var&gt;
&lt;/field&gt;

&lt;field
    property="coverageType"
    indexedListProperty="dependents"
    depends="requiredif"&gt;
  &lt;arg0 key="dependentlistForm.coverageType.label"/&gt;
  &lt;var&gt;
    &lt;var-name&gt;field[0]&lt;/var-name&gt;
    &lt;var-value&gt;lastName&lt;/var-value&gt;
  &lt;/var&gt;
  &lt;var&gt;
    &lt;var-name&gt;fieldIndexed[0]&lt;/var-name&gt;
    &lt;var-value&gt;true&lt;/var-value&gt;
  &lt;/var&gt;
  &lt;var&gt;
    &lt;var-name&gt;fieldTest[0]&lt;/var-name&gt;
    &lt;var-value&gt;NOTNULL&lt;/var-value&gt;
  &lt;/var&gt;
  &lt;var&gt;
    &lt;var-name&gt;field[1]&lt;/var-name&gt;
    &lt;var-value&gt;insureDependents&lt;/var-value&gt;
  &lt;/var&gt;
  &lt;var&gt;
    &lt;var-name&gt;fieldTest[1]&lt;/var-name&gt;
    &lt;var-value&gt;EQUAL&lt;/var-value&gt;
  &lt;/var&gt;
  &lt;var&gt;
    &lt;var-name&gt;fieldValue[1]&lt;/var-name&gt;
    &lt;var-value&gt;true&lt;/var-value&gt;
  &lt;/var&gt;
  &lt;var&gt;
    &lt;var-name&gt;fieldJoin&lt;/var-name&gt;
    &lt;var-value&gt;AND&lt;/var-value&gt;
  &lt;/var&gt;
&lt;/field&gt;

&lt;/form&gt;

</pre>

    <p>
    Which is read as follows:
    The firstName field is only required if the lastName field is non-null.
    Since fieldIndexed is true, it means that lastName must be a property of
    the same indexed field as firstName.
    Same thing for dob, except that we validate for date if not blank.
    </p>

    <p>
    The coverageType is only required if the lastName for the same indexed
    bean is not null, and also if the non-indexed field insureDependents is
    true.
    </p>

    <p>
    You can have an arbitrary number of fields by using the [n] syntax,
    the only restriction is that they must all be AND or OR, you can't mix.
    </p>

</div>
<h2 id="stopOnFirstError">Unstoppable JavaScript Validations</h2>
<div class="indent">

        <p>
        [Since Struts 1.2.0] You can force the clientside Javascript validation
        to check all constraints, instead of stopping at the first error.
        By setting a new property, <code>stopOnFirstError</code>, on the
        Validator PlugIn to false.
        </p>

        <p>
        Here's a sample configuration block that you could use in your
        Struts configuration file:
        </p>

      <pre>
<code>

  &lt;plug-in className="org.apache.struts.validator.ValidatorPlugIn"&gt;
  &lt;set-property property="pathnames"
   value="/WEB-INF/validator-rules.xml,/WEB-INF/validations.xml"/&gt;
  &lt;set-property property="stopOnFirstError" value="false"/&gt;
  &lt;/plug-in&gt;
  

</code>
</pre>

    </div>
<h2 id="api">Validator API Guide</h2>
<div class="indent">

    <p>
    A concise
    <a href="../api/org/apache/struts/validator/package-summary.html#package_description">
    Struts Validator API Guide</a> is available to help you get started.
    </p>

</div>
<h2 id="resources">Validator Resources</h2>
<div class="indent">

	<p>
    <a href="http://otn.oracle.com/oramag/oracle/04-jan/o14dev_struts.html">
    <strong>Check Your Form with Validator</strong>
</a> by James Holmes.
    Howto article in Oracle Magazine.
    </p>

    <p>
    <a href="http://www.raibledesigns.com/page/rd/20030226#struts_validator_validating_two_fields">
    <strong>Struts Validator: Validating Two Fields Match</strong>
</a> by Matt Raible.
    Howto article.
    </p>

    <p>
    <a href="http://www.strutskickstart.com/">
    <strong>DynaForms and the Validator</strong>
</a> by James Turner and Kevin Bedell.
    Sample chapter from
    <a href="http://www.strutskickstart.com/">Struts Kickstart</a>;
    available as a free download (PDF).
    </p>

    <p>
    <a href="http://www.manning.com/getpage.html?project=husted&amp;filename=chapters.html">
    <strong>Validating user input</strong>
</a> by David Winterfeldt and Ted Husted.
    Sample chapter from
    <a href="http://www.amazon.com/exec/obidos/ISBN=1930110502/hitchhikeguidetoA/">
    Struts in Action</a>;
    available as a free download (PDF).
    </p>

</div>
</div>
<!--end main-->
</div>
<!--end content-->
<div id="footer">
<img id="powered-logo" alt="Powered by Struts" src="../images/struts-power.gif" />
        Copyright (c) 2000-2005, The Apache Software Foundation <span class="noprint">- 
        <a href="http://wiki.apache.org/struts/StrutsDocComments">Comments?</a>
</span>
</div>
<!--end footer-->
</body>
</html>