tapestry-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From conflue...@apache.org
Subject [CONF] Apache Tapestry > Input Validation
Date Mon, 20 Dec 2010 09:01:00 GMT
    <base href="https://cwiki.apache.org/confluence">
            <link rel="stylesheet" href="/confluence/s/1810/9/12/_/styles/combined.css?spaceKey=TAPESTRY&amp;forWysiwyg=true"
<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/Input+Validation">Input
    <h4>Page <b>edited</b> by             <a href="https://cwiki.apache.org/confluence/display/~drobiazko">Igor
                         <h4>Changes (1)</h4>
<div id="page-diffs">
            <table class="diff" cellpadding="0" cellspacing="0">
            <tr><td class="diff-added-lines" style="background-color: #dfd;">{float:right}
<br>{info:title=Related Articles} <br>[Bean Validation] <br>{info} <br>{float}
<br> <br></td></tr>
            <tr><td class="diff-unchanged" >h1. Form Input and Validation <br>
            <tr><td class="diff-snipped" >...<br></td></tr>
</div>                            <h4>Full Content</h4>
                    <div class="notificationGreySide">
        <div class='navmenu' style='float:right; background:white; margin:3px; padding:3px'><div
class='panelMacro'><table class='infoMacro'><colgroup><col width='24'><col></colgroup><tr><td
valign='top'><img src="/confluence/images/icons/emoticons/information.gif" width="16"
height="16" align="absmiddle" alt="" border="0"></td><td><b>Related Articles</b><br
/><a href="/confluence/display/TAPESTRY/Bean+Validation" title="Bean Validation">Bean

<h1><a name="InputValidation-FormInputandValidation"></a>Form Input and

<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="InputValidation-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="#InputValidation-event.html">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 chance to create a temporary entity
object to be rendered, or to load an entity from a database to be editted.</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="InputValidation-TrackingValidationErrors"></a>Tracking Validation

<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

<h1><a name="InputValidation-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="#InputValidation-persist.html">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

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

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

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

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

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

    <span class="code-object">String</span> onSuccess()
        <span class="code-keyword">if</span> (!authenticator.isValid(userName,
            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>
        <span class="code-keyword">return</span> password;

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

    <span class="code-keyword">public</span> <span class="code-object">String</span>
        <span class="code-keyword">return</span> userName;

    <span class="code-keyword">public</span> void setUserName(<span class="code-object">String</span>
        userName = userName;

<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

<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="InputValidation-ConfiguringFieldsandLabels"></a>Configuring
Fields and Labels</h1>

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

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

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


            &lt;t:label <span class="code-keyword">for</span>=<span class="code-quote">"userName"</span>/&gt;:
            &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;
            &lt;t:label <span class="code-keyword">for</span>=<span class="code-quote">"password"</span>/&gt;:
            &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;
            &lt;input type=<span class="code-quote">"submit"</span> value=<span

<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 useability,
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="InputValidation-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="InputValidation-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="InputValidation-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="#InputValidation-localization.html">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>-message.</p>

	<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>-<em>validatorName</em>-message.</li>

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

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

<p>The <a href="#InputValidation-beaneditform.html">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="InputValidation-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>-<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-java">
  &lt;t:textfield t:id=<span class="code-quote">"ssn"</span> validate=<span

<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-message=Social security numbers are in the format 12-34-5678.

<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

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

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

<div class='table-wrap'>
<table class='confluenceTable'><tbody>
<td class='confluenceTd'> Validator </td>
<td class='confluenceTd'> Constraint Type </td>
<td class='confluenceTd'> Description </td>
<td class='confluenceTd'> Example </td>
<td class='confluenceTd'> email </td>
<td class='confluenceTd'><ul class="alternate" type="square">
<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>
<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>
<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>
<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>
<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>
<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 class='confluenceTd'> <tt>&lt;t:textfield value="otherfield" validate="regexp=^<a
class="createlink">a&#45;z</a>+$" /&gt;</tt> </td>
<td class='confluenceTd'> required </td>
<td class='confluenceTd'><ul class="alternate" type="square">
<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>

<h1><a name="InputValidation-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

<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

  . . .

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

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

<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>
    <span class="code-keyword">if</span> ("".equals(input)) <span class="code-keyword">return</span>

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

<p>The event handler method has precendence over the translator. Here it checks for
the empty string (and note that the input may be null!) 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 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:

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

<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 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>
        <a href="https://cwiki.apache.org/confluence/display/TAPESTRY/Input+Validation">View
        <a href="https://cwiki.apache.org/confluence/pages/diffpagesbyversion.action?pageId=22872109&revisedVersion=6&originalVersion=5">View

View raw message