tapestry-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From conflue...@apache.org
Subject [CONF] Apache Tapestry > Forms and Validation
Date Thu, 21 Jul 2011 15:39:00 GMT
<html>
<head>
    <base href="https://cwiki.apache.org/confluence">
            <link rel="stylesheet" href="/confluence/s/2042/9/12/_/styles/combined.css?spaceKey=TAPESTRY&amp;forWysiwyg=true"
type="text/css">
    </head>
<body style="background: white;" bgcolor="white" class="email-body">
<div id="pageContent">
<div id="notificationFormat">
<div class="wiki-content">
<div class="email">
    <h2><a href="https://cwiki.apache.org/confluence/display/TAPESTRY/Forms+and+Validation">Forms
and Validation</a></h2>
    <h4>Page <b>edited</b> by             <a href="https://cwiki.apache.org/confluence/display/~demey.emmanuel@gmail.com">DEMEY
Emmanuel</a>
    </h4>
        <br/>
                         <h4>Changes (10)</h4>
                                 
    
<div id="page-diffs">
                    <table class="diff" cellpadding="0" cellspacing="0">
    
            <tr><td class="diff-snipped" >...<br></td></tr>
            <tr><td class="diff-unchanged" >The template for a page contains a
minimal amount of Tapestry instrumentation: <br> <br></td></tr>
            <tr><td class="diff-changed-lines" ><span class="diff-deleted-words"style="color:#999;background-color:#fdd;text-decoration:line-through;">{code:java}</span>
<span class="diff-added-words"style="background-color: #dfd;">{code:html}</span>
<br></td></tr>
            <tr><td class="diff-unchanged" >&lt;html xmlns:t=&quot;http://tapestry.apache.org/schema/tapestry_5_1_0.xsd&quot;&gt;
<br>    &lt;head&gt; <br></td></tr>
            <tr><td class="diff-snipped" >...<br></td></tr>
            <tr><td class="diff-unchanged" >The message can be customized by adding
an entry to the page&#39;s [message catalog|Localization] (or the containing component&#39;s
message catalog). As with any localized property, this can also go into the application&#39;s
message catalog. <br> <br></td></tr>
            <tr><td class="diff-changed-lines" >The first key checked is <span
class="diff-changed-words">_formId_\-_fieldId_\-_validatorName_<span class="diff-added-chars"style="background-color:
#dfd;">\</span>-message.</span> <br></td></tr>
            <tr><td class="diff-unchanged" > <br>* formId: the local component
id of the Form component <br>* fieldId: the local component id of the field (TextField,
etc.) <br>* validatorName: the name of the validator, i.e., &quot;required&quot;
or &quot;minlength&quot; <br></td></tr>
            <tr><td class="diff-changed-lines" >If there is not message for that
key, a second check is made, for <span class="diff-changed-words">_fieldId_<span
class="diff-added-chars"style="background-color: #dfd;">\</span>-_validatorName_<span
class="diff-added-chars"style="background-color: #dfd;">\</span>-message.</span>
<br></td></tr>
            <tr><td class="diff-unchanged" > <br>If that does not match
a message, then the built-in default validation message is used. <br></td></tr>
            <tr><td class="diff-snipped" >...<br></td></tr>
            <tr><td class="diff-unchanged" >This is useful when the validation
constraint is awkward to enter inline, such as a regular expression for use with the regexp
validator. <br> <br></td></tr>
            <tr><td class="diff-changed-lines" >The key here is similar to customizing
the validation message: _formId_\-_fieldId_\-_validatorName_ or just <span class="diff-changed-words">_fieldId_<span
class="diff-added-chars"style="background-color: #dfd;">\</span>-_validatorName_.</span>
<br></td></tr>
            <tr><td class="diff-unchanged" > <br>For example, your template
may have the following: <br> <br></td></tr>
            <tr><td class="diff-changed-lines" ><span class="diff-deleted-words"style="color:#999;background-color:#fdd;text-decoration:line-through;">{code:java}</span>
<span class="diff-added-words"style="background-color: #dfd;">{code:html}</span>
<br></td></tr>
            <tr><td class="diff-unchanged" >  &lt;t:textfield t:id=&quot;ssn&quot;
validate=&quot;required,regexp&quot;/&gt; <br>{code} <br></td></tr>
            <tr><td class="diff-snipped" >...<br></td></tr>
            <tr><td class="diff-unchanged" > <br>| Validator | Constraint
Type | Description | Example | <br></td></tr>
            <tr><td class="diff-changed-lines" >| email | - <span class="diff-added-words"style="background-color:
#dfd;"> </span> | Ensures that the given input is a valid e-mail address | {{&lt;t:textfield
value=&quot;email&quot; validate=&quot;email&quot; /&gt;}} | <br></td></tr>
            <tr><td class="diff-unchanged" >| max | long | Enforces a maximum
integer value | {{&lt;t:textfield value=&quot;age&quot; validate=&quot;max=120,min=0&quot;
/&gt;}} | <br>| maxLength | int | Makes sure that a string value has a maximum length
| {{&lt;t:textfield value=&quot;zip&quot; validate=&quot;maxlength=7&quot;
/&gt;}} | <br>| min | long | Enforces a minimum integer value | {{&lt;t:textfield
value=&quot;age&quot; validate=&quot;max=120,min=0&quot; /&gt;}} | <br>|
minLength | int | Makes sure that a string value has a minimum length | {{&lt;t:textfield
value=&quot;somefield&quot; validate=&quot;minlength=1&quot; /&gt;}} |
<br></td></tr>
            <tr><td class="diff-changed-lines" >| regexp | pattern | Makes sure
that a string value conforms to a given pattern | {{&lt;t:textfield value=&quot;otherfield&quot;
<span class="diff-deleted-words"style="color:#999;background-color:#fdd;text-decoration:line-through;">validate=&quot;regexp=^[a-z]+$&quot;</span>
<span class="diff-added-words"style="background-color: #dfd;">validate=&quot;regexp=\^}}{{[a-z|a-z]}}{{\+$&quot;</span>
/&gt;}} | <br></td></tr>
            <tr><td class="diff-changed-lines" >| required | - <span class="diff-added-words"style="background-color:
#dfd;"> </span> | Makes sure that a string value is not null and not the empty string
| {{&lt;t:textfield value=&quot;name&quot; validate=&quot;required&quot;
/&gt;}} | <br></td></tr>
            <tr><td class="diff-unchanged" > <br></td></tr>
            <tr><td class="diff-added-lines" style="background-color: #dfd;">h1.
Validation Macros <br> <br>Since Tapestry 5.2, we can create validation macros,
wich will contain a list of validators. This mechanism is very useful for combining your validators.
We just have to contribute to the ValidatorMacro Service in your AppModule, by adding a new
entry to the configuration object. The first parameter is the name of your macro, the second
is a comma-separated list of validators. <br> <br>{code:java} <br>@Contribute(ValidatorMacro.class)
<br>public static void combinePasswordValidators(MappedConfiguration&lt;String,
String&gt; configuration) { <br>      configuration.add(&quot;password&quot;,&quot;required,minlength=5,maxlength=15,&quot;);
<br>} <br>{code} <br> <br>Then, we can use this new macro in our Template
or Java Class. <br> <br>{code:html} <br>&lt;input t:type=&quot;textField&quot;
t:id=&quot;password&quot; t:validate=&quot;password&quot; /&gt; <br>{code}
<br> <br>{code:java} <br>@Validate(&quot;password&quot;) <br>private
String password; <br>{code} <br> <br></td></tr>
            <tr><td class="diff-unchanged" >h1. Overriding the Translator with
Events <br> <br></td></tr>
            <tr><td class="diff-snipped" >...<br></td></tr>
            <tr><td class="diff-unchanged" >{code} <br> <br></td></tr>
            <tr><td class="diff-changed-lines" >The event handler method has precedence
over the translator. Here it checks for the empty string (and note that the input may be <span
class="diff-changed-words">null<span class="diff-added-chars"style="background-color:
#dfd;">\</span>!)</span> and evaluates that as zero. <br></td></tr>
            <tr><td class="diff-unchanged" > <br>Again, returning null lets
the normal translator do its work. <br></td></tr>
            <tr><td class="diff-snipped" >...<br></td></tr>
    
            </table>
    </div>                            <h4>Full Content</h4>
                    <div class="notificationGreySide">
        <div class='navmenu' style='float:right; background:#eee; margin:3px; padding:3px'><table
class="tableview" width="100%">
            <tr><th style="padding: 3px 3px 3px 0px">Related Articles</th></tr>
                        <tr>
            <td>
                                 <span class="icon icon-page" title=Page>Page:</span>
                         <a href="/confluence/display/TAPESTRY/Forms+and+Validation">Forms
and Validation</a>
        
                                            </td>
        </tr>
                <tr>
            <td>
                                 <span class="icon icon-page" title=Page>Page:</span>
                         <a href="/confluence/display/TAPESTRY/Bean+Validation">Bean
Validation</a>
        
                                            </td>
        </tr>
                <tr>
            <td>
                                 <span class="icon icon-page" title=Page>Page:</span>
                         <a href="/confluence/display/TAPESTRY/Forms+and+Form+Components+FAQ">Forms
and Form Components FAQ</a>
        
                                            </td>
        </tr>
            </table>
</div>

<p>The life's blood of any application is form input; this is the most effective way
to gather significant information from the user. Whether it's a search form, a login screen
or a multi-page registration wizard, forms are how the user really expresses themselves to
the application.</p>

<p>Tapestry excels at creating forms and validating input. Input validation is declarative,
meaning you simply tell Tapestry what validations to apply to a given field, and it takes
care of it on the server and (once implemented) on the client as well.</p>

<p>Finally, Tapestry is able to not only present the errors back to the user, but to
decorate the fields and the labels for the fields, marking them as containing errors (primarily,
using CSS effects).</p>

<h1><a name="FormsandValidation-Formcomponent"></a>Form component</h1>

<p>The core of Tapestry's form support is the <a href="http://tapestry.apache.org/current/tapestry-core/ref/org/apache/tapestry5/corelib/components/Form.html"
class="external-link" rel="nofollow">Form</a> component. The Form component encloses
(wraps around) all the other <em>field components</em> such as <a href="http://tapestry.apache.org/current/tapestry-core/ref/org/apache/tapestry5/corelib/components/TextField.html"
class="external-link" rel="nofollow">TextField</a>, <a href="http://tapestry.apache.org/current/tapestry-core/ref/org/apache/tapestry5/corelib/components/TextArea.html"
class="external-link" rel="nofollow">TextArea</a>, <a href="http://tapestry.apache.org/current/tapestry-core/ref/org/apache/tapestry5/corelib/components/Checkbox.html"
class="external-link" rel="nofollow">Checkbox</a>, etc.</p>

<p>The Form component generates a number of <a href="/confluence/display/TAPESTRY/Component+Events"
title="Component Events">component events</a> that you may provide event handler
methods for.</p>

<p>When rendering, the Form component emits two notifications: first, "prepareForRender",
then "prepare". These allow the Form's container to setup any fields or properties that will
be referenced in the form. For example, this is a good place to create a temporary entity
object to be rendered, or to load an entity from a database to be edited.</p>

<p>When user submits the form on the client, a series of steps occur on the server.</p>

<p>First, the Form emits a "prepareForSubmit" notification, then a "prepare" notification.
These allow the container to ensure that objects are set up and ready to receive information
from the form submission.</p>

<p>Next, all the fields inside the form are activated to pull values out of the incoming
request, validate them and (if valid) store the changes.</p>

<p><em>For Tapestry 4 Users:</em> Tapestry 5 does not use the fragile "form
rewind" approach from Tapestry 4. Instead, a hidden field generated during the render stores
the information needed to process the form submission.</p>

<p>After the fields have done their processing, the Form emits a "validateForm" event.
This is a chance to perform cross-form validation that can't be described declaratively.</p>

<p>Next, the Form determines if there have been any validation errors. If there have
been, then the submission is considered a failure, and a "failure" event is emitted. If there
have been no validation errors, then a "success" event is emitted.</p>

<p>Last, the Form emits a "submit" event (for logic that doesn't care about success
or failure).</p>

<h1><a name="FormsandValidation-TrackingValidationErrors"></a>Tracking Validation
Errors</h1>

<p>Associated with the Form is an <a href="http://tapestry.apache.org/current/apidocs/org/apache/tapestry5/ValidationTracker.html"
class="external-link" rel="nofollow">ValidationTracker</a> that tracks all the provided
user input and validation errors for every field in the form. The tracker can be provided
to the Form via the Form's tracker parameter, but this is rarely necessary.</p>

<p>The Form includes methods <tt>isValid()</tt> and <tt>getHasErrors()</tt>,
which are used to see if the Form's validation tracker contains any errors.</p>

<p>In your own logic, it is possible to record your own errors. Form includes two different
versions of method <tt>recordError()</tt>, one of which specifies a <a href="http://tapestry.apache.org/current/apidocs/org/apache/tapestry5/Field.html"
class="external-link" rel="nofollow">Field</a> (an interface implemented by all form
element components), and one of which is for "global" errors, unassociated with any particular
field.</p>

<h1><a name="FormsandValidation-StoringDataBetweenRequests"></a>Storing
Data Between Requests</h1>

<p>As with other action requests, the result of a form submission is to send a redirect
to the client which re-renders the page. The ValidationTracker must be stored <a href="/confluence/display/TAPESTRY/Persistent+Page+Data"
title="Persistent Page Data">persistently</a> between requests, or all the validation
information will be lost (the default ValidationTracker provided by the Form is persistent).</p>

<p>Likewise, the individual fields updated by the components should also be persistent.</p>

<p>For example, a Login page, which collects a user name and a password, might look
like:</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
<span class="code-keyword">public</span> class Login
{
    @Persist
    <span class="code-keyword">private</span> <span class="code-object">String</span>
userName;

    <span class="code-keyword">private</span> <span class="code-object">String</span>
password;

    @Inject
    <span class="code-keyword">private</span> UserAuthenticator authenticator;

    @Component(id = <span class="code-quote">"password"</span>)
    <span class="code-keyword">private</span> PasswordField passwordField;

    @Component
    <span class="code-keyword">private</span> Form form;

    <span class="code-object">String</span> onSuccess()
    {
        <span class="code-keyword">if</span> (!authenticator.isValid(userName,
password))
        {
            form.recordError(passwordField, <span class="code-quote">"Invalid user name
or password."</span>);
            <span class="code-keyword">return</span> <span class="code-keyword">null</span>;
        }

        <span class="code-keyword">return</span> <span class="code-quote">"PostLogin"</span>;
    }

    <span class="code-keyword">public</span> <span class="code-object">String</span>
getPassword()
    {
        <span class="code-keyword">return</span> password;
    }

    <span class="code-keyword">public</span> void setPassword(<span class="code-object">String</span>
password)
    {
        password = password;
    }

    <span class="code-keyword">public</span> <span class="code-object">String</span>
getUserName()
    {
        <span class="code-keyword">return</span> userName;
    }

    <span class="code-keyword">public</span> void setUserName(<span class="code-object">String</span>
userName)
    {
        userName = userName;
    }
}
</pre>
</div></div>

<p>Because of the the fact that a form submission is <em>two</em> requests
(the submission itself, then a re-render of the page), it is necessary to make the value stored
in the userName field persist between the two requests. This would be necessary for the password
field as well, except that the <a href="http://tapestry.apache.org/current/tapestry-core/ref/org/apache/tapestry5/corelib/components/PasswordField.html"
class="external-link" rel="nofollow">PasswordField</a> component never renders a
value.</p>

<p>Note that the onSuccess() method is not public; event handler methods can have any
visibility, even private. Package private (that is, no modifier) is the typical use, as it
allows the component to be tested, from a test case class in the same package.</p>

<p>The Form only emits a "success" event if the there are no prior validation errors.
This means it is not necessary to write <tt>if (form.getHasErrors()) return;</tt>
as the first line of the method.</p>

<p>Finally, notice how business logic fits into validation. The UserAuthenticator service
is responsible for ensuring that the userName and (plaintext) password are valid. When it
returns false, we ask the Form component to record an error. We provide the PasswordField
instance as the first parameter; this ensures that the password field, and its label, are
decorated when the Form is re-rendered, to present the errors to the user.</p>

<h1><a name="FormsandValidation-ConfiguringFieldsandLabels"></a>Configuring
Fields and Labels</h1>

<p>The template for a page contains a minimal amount of Tapestry instrumentation:</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-html">
<span class="code-tag">&lt;html <span class="code-keyword">xmlns:t</span>=<span
class="code-quote">"http://tapestry.apache.org/schema/tapestry_5_1_0.xsd"</span>&gt;</span>
    <span class="code-tag">&lt;head&gt;</span>
        <span class="code-tag">&lt;title&gt;</span>Login<span class="code-tag">&lt;/title&gt;</span>
    <span class="code-tag">&lt;/head&gt;</span>
    <span class="code-tag">&lt;body&gt;</span>
        <span class="code-tag">&lt;h1&gt;</span>Please Login<span class="code-tag">&lt;/h1&gt;</span>

        <span class="code-tag">&lt;form t:type=<span class="code-quote">"form"</span>
t:id=<span class="code-quote">"form"</span>&gt;</span>

            <span class="code-tag">&lt;t:errors/&gt;</span>

            <span class="code-tag">&lt;t:label for=<span class="code-quote">"userName"</span>/&gt;</span>:
            <span class="code-tag">&lt;input t:type=<span class="code-quote">"TextField"</span>
t:id=<span class="code-quote">"userName"</span> t:validate=<span class="code-quote">"required,minlength=3"</span>
size=<span class="code-quote">"30"</span>/&gt;</span>
            <span class="code-tag">&lt;br/&gt;</span>
            <span class="code-tag">&lt;t:label for=<span class="code-quote">"password"</span>/&gt;</span>:
            <span class="code-tag">&lt;input t:type=<span class="code-quote">"PasswordField"</span>
t:id=<span class="code-quote">"password"</span> t:validate=<span class="code-quote">"required,minlength=3"</span>
size=<span class="code-quote">"30"</span>/&gt;</span>
            <span class="code-tag">&lt;br/&gt;</span>
            <span class="code-tag">&lt;input type=<span class="code-quote">"submit"</span>
value=<span class="code-quote">"Login"</span>/&gt;</span>
        <span class="code-tag">&lt;/form&gt;</span>
    <span class="code-tag">&lt;/body&gt;</span>
<span class="code-tag">&lt;/html&gt;</span>
</pre>
</div></div>

<p>The Tapestry Form component is responsible for creating the necessary URL for the
form submission (this is Tapestry's responsibility, not yours).</p>

<p>The <a href="http://tapestry.apache.org/current/tapestry-core/ref/org/apache/tapestry5/corelib/components/Errors.html"
class="external-link" rel="nofollow">Errors</a> component must be placed inside a
Form, it outputs all of the errors for all the fields within the Form as a single list. It
uses some simple styling to make the result more presentable.</p>

<p>Each field component, such as the TextField, is paired with a <a href="http://tapestry.apache.org/current/tapestry-core/ref/org/apache/tapestry5/corelib/components/Label.html"
class="external-link" rel="nofollow">Label</a> component. The Label will render out
a &lt;label&gt; element connected to the field. This is very important for usability,
especially for users with visual disabilities. It also means you can click on the label text
to move the cursor to the corresponding field.</p>

<p>The <tt>for</tt> parameter of the Label is the id of a component.</p>

<p>For the TextField, we provide a component id, userName. We could specify the <tt>value</tt>
parameter, but the default is to match the TextField's id against a property of the container,
the Login page, if such a property exists.</p>

<p>As a rule of thumb, you should always give your fields a specific id (this id will
be used to generate the <tt>name</tt> and <tt>id</tt> attributes of
the rendered tag). Being allowed to omit the value parameter helps to keep the template from
getting too cluttered.</p>

<p>The <tt>validate</tt> parameter identifies what validations should occur
for the field. This is a list of validator names. Validators are configured within Tapestry,
and the list of available validators is extensible. "required" is a name of one of the built-in
validators, that ensures that the submitted value is not the empty string. Likewise, "minlen"
ensures that the value has the specified minimum length.</p>

<p>The <tt>validate</tt> parameter was placed within the Tapestry namespace
using the <tt>t:</tt> prefix. This is not strictly necessary, as the template
is <em>well formed</em> either way. However, putting the Tapestry specific values
into the Tapestry namespace ensures that the template will itself be <em>valid</em>.</p>

<h1><a name="FormsandValidation-ErrorsandDecorations"></a>Errors and Decorations</h1>

<p><b>Note: This section has not been updated to reflect the introduction of client-side
input validation.</b></p>

<p>When you first activate the Login page, the fields and forms will render normally,
awaiting input:</p>


<p><span class="image-wrap" style=""><img src="/confluence/download/attachments/22872109/validation_initial.png?version=1&amp;modificationDate=1276691999000"
title="Initial form presentation" style="border: 0px solid black" /></span></p>

<p>Notice how the Label components are displaying the textual names for the fields.
Given that we have not done any explicit configuration, what's happened is that the component's
ids ("userName" and "password") have been converted to "User Name" and "Password".</p>

<p>If you just submit the form as is, the fields will violate the "required" constraint
and the page will be redisplayed to present those errors to the user:</p>

<p><span class="image-wrap" style=""><img src="/confluence/download/attachments/22872109/validation_errors.png?version=1&amp;modificationDate=1276691999000"
title="Errors and decorations" style="border: 0px solid black" /></span></p>

<p>There's a couple of subtle things going on here. First, Tapestry tracks <em>all</em>
the errors for <em>all</em> the fields. The Errors component has displayed them
at the top of the form. Further, the <em>default validation decorator</em> has
added decorations to the labels and the fields, adding "t-error" to the CSS class for the
fields and labels. Tapestry provides a default CSS stylesheet that combines with the "t-error"
class to make things turn red.</p>

<p>Next, we'll fill in the user name but not provide enough characters for password.</p>


<p><span class="image-wrap" style=""><img src="/confluence/download/attachments/22872109/validation_minlength.png?version=1&amp;modificationDate=1276692000000"
title="Minlength error message" style="border: 0px solid black" /></span></p>

<p>The user name field is OK, but there's an error on just the password field. The PasswordField
component always displays a blank value by default, otherwise we'd see the partial password
displayed inside.</p>

<p>If you type in enough characters and submit, we see how the logic inside the Login
page can attach errors to fields:</p>


<p><span class="image-wrap" style=""><img src="/confluence/download/attachments/22872109/validation_password.png?version=1&amp;modificationDate=1276692000000"
title="Application supplied errors" style="border: 0px solid black" /></span></p>

<p>This is nice and seamless; the same look and feel and behavior for both the built-in
validators, and for errors generated based on application logic.</p>

<h1><a name="FormsandValidation-CentralizingValidationwith@Validate"></a>Centralizing
Validation with @Validate</h1>

<p>The @<a href="http://tapestry.apache.org/current/apidocs/org/apache/tapestry5/beaneditor/Validate.html"
class="external-link" rel="nofollow">Validate</a> annotation can take the place of
the validate parameter of TextField, PasswordField, TextArea and other components. When the
validate parameter is not bound, the component will check for the @Validate annotation and
use its value as the validation definition.</p>

<p>The annotation may be placed on the getter or setter method, or on the field itself.</p>

<h1><a name="FormsandValidation-CustomizingValidationMessages"></a>Customizing
Validation Messages</h1>

<p>Each validator (such as "required" or "minlength") has a default message used (on
the client side and the server side) when the constraint is violated; that is, when the user
input is not valid.</p>

<p>The message can be customized by adding an entry to the page's <a href="/confluence/display/TAPESTRY/Localization"
title="Localization">message catalog</a> (or the containing component's message catalog).
As with any localized property, this can also go into the application's message catalog.</p>

<p>The first key checked is <em>formId</em>&#45;<em>fieldId</em>&#45;<em>validatorName</em>&#45;message.</p>

<ul>
	<li>formId: the local component id of the Form component</li>
	<li>fieldId: the local component id of the field (TextField, etc.)</li>
	<li>validatorName: the name of the validator, i.e., "required" or "minlength"<br/>
If there is not message for that key, a second check is made, for <em>fieldId</em>&#45;<em>validatorName</em>&#45;message.</li>
</ul>


<p>If that does not match a message, then the built-in default validation message is
used.</p>

<h1><a name="FormsandValidation-CustomizingValidationMessages%2FBeanEditForm"></a>Customizing
Validation Messages / BeanEditForm</h1>

<p>The <a href="/confluence/display/TAPESTRY/BeanEditForm+Guide" title="BeanEditForm
Guide">BeanEditForm</a> component also supports validation message customizing. The
search is the similar; the <em>formId</em> is the component id of the BeanEditForm
component (not the Form component it contains). The <em>fieldId</em> is the property
name.</p>

<h1><a name="FormsandValidation-ConfiguringValidatorContraintsintheMessageCatalog"></a>Configuring
Validator Contraints in the Message Catalog</h1>

<p>It is possible to omit the validation constraint from the validator parameter (or
@Validator annotation), in which case it is expected to be stored in the message catalog.</p>

<p>This is useful when the validation constraint is awkward to enter inline, such as
a regular expression for use with the regexp validator.</p>

<p>The key here is similar to customizing the validation message: <em>formId</em>&#45;<em>fieldId</em>&#45;<em>validatorName</em>
or just <em>fieldId</em>&#45;<em>validatorName</em>.</p>

<p>For example, your template may have the following:</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-html">
  <span class="code-tag">&lt;t:textfield t:id=<span class="code-quote">"ssn"</span>
validate=<span class="code-quote">"required,regexp"</span>/&gt;</span>
</pre>
</div></div>

<p>And your message catalog can contain:</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
ssn-regexp=\d{3}-\d{2}-\d{4}
ssn-regexp-message=Social security numbers are in the format 12-34-5678.
</pre>
</div></div>

<p>This technique also works with the BeanEditForm; as with validation messages, the
formId is the BeanEditForm component's id, and the fieldId is the name of the property being
editted.</p>

<h1><a name="FormsandValidation-AvailableValidators"></a>Available Validators</h1>

<p>Currently Tapestry provides the following built-in validators:</p>

<div class='table-wrap'>
<table class='confluenceTable'><tbody>
<tr>
<td class='confluenceTd'> Validator </td>
<td class='confluenceTd'> Constraint Type </td>
<td class='confluenceTd'> Description </td>
<td class='confluenceTd'> Example </td>
</tr>
<tr>
<td class='confluenceTd'> email </td>
<td class='confluenceTd'><ul class="alternate" type="square">
	<li></li>
</ul>
</td>
<td class='confluenceTd'> Ensures that the given input is a valid e-mail address </td>
<td class='confluenceTd'> <tt>&lt;t:textfield value="email" validate="email"
/&gt;</tt> </td>
</tr>
<tr>
<td class='confluenceTd'> max </td>
<td class='confluenceTd'> long </td>
<td class='confluenceTd'> Enforces a maximum integer value </td>
<td class='confluenceTd'> <tt>&lt;t:textfield value="age" validate="max=120,min=0"
/&gt;</tt> </td>
</tr>
<tr>
<td class='confluenceTd'> maxLength </td>
<td class='confluenceTd'> int </td>
<td class='confluenceTd'> Makes sure that a string value has a maximum length </td>
<td class='confluenceTd'> <tt>&lt;t:textfield value="zip" validate="maxlength=7"
/&gt;</tt> </td>
</tr>
<tr>
<td class='confluenceTd'> min </td>
<td class='confluenceTd'> long </td>
<td class='confluenceTd'> Enforces a minimum integer value </td>
<td class='confluenceTd'> <tt>&lt;t:textfield value="age" validate="max=120,min=0"
/&gt;</tt> </td>
</tr>
<tr>
<td class='confluenceTd'> minLength </td>
<td class='confluenceTd'> int </td>
<td class='confluenceTd'> Makes sure that a string value has a minimum length </td>
<td class='confluenceTd'> <tt>&lt;t:textfield value="somefield" validate="minlength=1"
/&gt;</tt> </td>
</tr>
<tr>
<td class='confluenceTd'> regexp </td>
<td class='confluenceTd'> pattern </td>
<td class='confluenceTd'> Makes sure that a string value conforms to a given pattern
</td>
<td class='confluenceTd'> <tt>&lt;t:textfield value="otherfield" validate="regexp=&#94;</tt><tt><a
href="/confluence/pages/createpage.action?spaceKey=TAPESTRY&amp;title=a-z&amp;linkCreation=true&amp;fromPageId=22872109"
class="createlink">a-z</a></tt><tt>&#43;$" /&gt;</tt> </td>
</tr>
<tr>
<td class='confluenceTd'> required </td>
<td class='confluenceTd'><ul class="alternate" type="square">
	<li></li>
</ul>
</td>
<td class='confluenceTd'> Makes sure that a string value is not null and not the empty
string </td>
<td class='confluenceTd'> <tt>&lt;t:textfield value="name" validate="required"
/&gt;</tt> </td>
</tr>
</tbody></table>
</div>


<h1><a name="FormsandValidation-ValidationMacros"></a>Validation Macros</h1>

<p>Since Tapestry 5.2, we can create validation macros, wich will contain a list of
validators. This mechanism is very useful for combining your validators. We just have to contribute
to the ValidatorMacro Service in your AppModule, by adding a new entry to the configuration
object. The first parameter is the name of your macro, the second is a comma-separated list
of validators.</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
@Contribute(ValidatorMacro.class)
<span class="code-keyword">public</span> <span class="code-keyword">static</span>
void combinePasswordValidators(MappedConfiguration&lt;<span class="code-object">String</span>,
<span class="code-object">String</span>&gt; configuration) {
      configuration.add(<span class="code-quote">"password"</span>,<span class="code-quote">"required,minlength=5,maxlength=15,"</span>);
}
</pre>
</div></div>

<p>Then, we can use this new macro in our Template or Java Class.</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-html">
<span class="code-tag">&lt;input t:type=<span class="code-quote">"textField"</span>
t:id=<span class="code-quote">"password"</span> t:validate=<span class="code-quote">"password"</span>
/&gt;</span>
</pre>
</div></div>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
@Validate(<span class="code-quote">"password"</span>)
<span class="code-keyword">private</span> <span class="code-object">String</span>
password;
</pre>
</div></div>

<h1><a name="FormsandValidation-OverridingtheTranslatorwithEvents"></a>Overriding
the Translator with Events</h1>

<p>The TextField, PasswordField and TextArea components all have a translate parameter,
a <a href="http://tapestry.apache.org/current/apidocs/org/apache/tapestry5/FieldTranslator.html"
class="external-link" rel="nofollow">FieldTranslator</a> object that is used to convert
values on the server side to strings on the client side.</p>

<p>In most cases, the translate parameter is not set explicitly; Tapestry derives an
appropriate value based on the type of property being editted by the field.</p>

<p>In certain cases, you may want to override the translator. This can be accomplished
using two events triggered on the component, "toclient" and "parseclient".</p>

<p>The "toclient" event is passed the current object value and returns a string, which
will be the default value for the field. When there is no event handler, or when the event
handler returns null, the default Translator is used to convert the server side value to a
string.</p>

<p>For example, you may have a quantity field that you wish to display as blank, rather
than zero, initially:</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
  &lt;t:textfield t:id=<span class="code-quote">"quantity"</span> size=<span
class="code-quote">"10"</span>/&gt;

  . . .

  <span class="code-keyword">private</span> <span class="code-object">int</span>
quantity;

  <span class="code-object">String</span> onToClientFromQuantity()
  {
    <span class="code-keyword">if</span> (quantity == 0) <span class="code-keyword">return</span>
"";

    <span class="code-keyword">return</span> <span class="code-keyword">null</span>;
  }
</pre>
</div></div>

<p>This is good so far, but if the field is optional and the user submits the form,
you'll get a validation error, because the empty string is not valid as an integer.</p>

<p>That's where the "parseclient" event comes in:</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
  <span class="code-object">Object</span> onParseClientFromQuantity(<span class="code-object">String</span>
input)
  {
    <span class="code-keyword">if</span> ("".equals(input)) <span class="code-keyword">return</span>
0;

    <span class="code-keyword">return</span> <span class="code-keyword">null</span>;
  }
</pre>
</div></div>

<p>The event handler method has precedence over the translator. Here it checks for the
empty string (and note that the input may be null&#33;) and evaluates that as zero.</p>

<p>Again, returning null lets the normal translator do its work.</p>

<p>The event handler may also throw a <a href="http://tapestry.apache.org/current/apidocs/org/apache/tapestry5/ValidationException.html"
class="external-link" rel="nofollow">ValidationException</a> to indicate a value
that can't be parsed.</p>

<p>Now, what if you want to perform your own custom validation? That's another event:
"validate":</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
  void onValidateFromCount(<span class="code-object">Integer</span> value) <span
class="code-keyword">throws</span> ValidationException
  {
    <span class="code-keyword">if</span> (value.equals(13)) <span class="code-keyword">throw</span>
<span class="code-keyword">new</span> ValidationException(<span class="code-quote">"Thirteen
is an unlucky number."</span>);
  }
</pre>
</div></div>

<p>This event gets fired <b>after</b> the normal validators. It is passed
the <em>parsed</em> value (not the string from the client, but the object value
from the translator, or from the "parseclient" event handler).</p>

<p>The method may not return a value, but may throw a ValidationException to indicate
a problem with the value.</p>

<p><b>Caution:</b> These events are exclusively on the <em>server
side</em>. This means that, in certain circumstances, an input value will be rejected
on the client side even though it is valid on the server side. You may need to disable client-side
validation in order to use this feature.</p>
    </div>
        <div id="commentsSection" class="wiki-content pageSection">
        <div style="float: right;">
            <a href="https://cwiki.apache.org/confluence/users/viewnotifications.action"
class="grey">Change Notification Preferences</a>
        </div>
        <a href="https://cwiki.apache.org/confluence/display/TAPESTRY/Forms+and+Validation">View
Online</a>
        |
        <a href="https://cwiki.apache.org/confluence/pages/diffpagesbyversion.action?pageId=22872109&revisedVersion=14&originalVersion=13">View
Changes</a>
            </div>
</div>
</div>
</div>
</div>
</body>
</html>

Mime
View raw message