Re: i18n docs

Gregor Horvath <gh-LfrpOBifzZo+ytmZ3SK/[email protected]>
Newsgroups gmane.comp.python.formencode
Organization Ing. Gregor Horvath, Industrieberatung & Softwareentwicklung
Message-ID <[email protected]>
Ian Bicking schrieb:

> Can someone write some i18n docs?  There doesn't seem to be anything.

see attached a html doc. I added a section by hand.

Hope this answers all questions.

Gregor

-------------------------------------------------------------------------
Take Surveys. Earn Cash. Influence the Future of IT
Join SourceForge.net's Techsay panel and you'll get the chance to share your
opinions on IT & business topics through brief surveys-and earn cash
http://www.techsay.com/default.php?page=join.php&p=sourceforge&CID=DEVDEV

_______________________________________________
FormEncode-discuss mailing list
FormEncode-discuss-5NWGOfrQmneRv+LV9MX5uipxlwaOVQ5f@public.gmane.org
https://lists.sourceforge.net/lists/listinfo/formencode-discuss
Validator.html (text/html, 34.9 KB)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html><head>

  
  <meta content="text/html; charset=utf-8" http-equiv="Content-Type"><title>FormEncode Validation</title>
    
    <link href="Validator-Dateien/layout.css" type="text/css" rel="stylesheet"></head><body>
    <div id="page">
      <h1 class="doc-title"><a>FormEncode</a></h1>
      <div id="navcontainer">
		    <ul id="navlist">
          <li class="pagenav">
            <ul>
              <li class="page_item">
                <a href="http://formencode.org/index.html" title="Project Home / Index">FormEncode</a>
              </li>
              <li class="page_item">
                <a href="http://formencode.org/module-index.html" title="formencode package and module reference">Modules</a>
              </li>
              
              
              
              <li>
                <a href="http://formencode.org/community.html" title="Mailing List">Discuss</a>
              </li>
              
	      <li>
	        <a href="http://formencode.org/Validator.html">Documentation</a>
	      </li>
            </ul>
          </li>
        </ul>
      </div>
      
      <hr>
      
      <div id="content"><div class="rst-doc">
  
  <h1 class="pudge-member-page-heading">FormEncode Validation</h1>
  
  <table class="docinfo" frame="void" rules="none">
<col class="docinfo-name">
<col class="docinfo-content">
<tbody valign="top">
<tr><th class="docinfo-name">Author:</th>
<td>Ian Bicking &lt;<a href="mailto:[email protected]" class="reference">[email protected]</a>&gt;</td></tr>
<tr><th class="docinfo-name">Revision:</th>
<td>2120</td></tr>
<tr><th class="docinfo-name">Date:</th>
<td>2006-12-06 12:58:17 -0600 (Wed, 06 Dec 2006)</td></tr>
</tbody>
</table>

  <!-- comment (set Emacs mode) -*- doctest -*-

>>> import sys
>>> import formencode -->
<div class="contents topic">
<p class="topic-title first"><a id="contents" name="contents">Contents</a></p>
<ul class="simple">
<li><a href="#introduction" id="id5" name="id5" class="reference">Introduction</a></li>
<li><a href="#using-validation" id="id6" name="id6" class="reference">Using Validation</a><ul>
<li><a href="#available-validators" id="id7" name="id7" class="reference">Available Validators</a></li>
<li><a href="#compound-validators" id="id8" name="id8" class="reference">Compound Validators</a></li>
<li><a href="#writing-your-own-validator" id="id9" name="id9" class="reference">Writing Your Own Validator</a></li>
<li><a href="#other-validator-usage" id="id10" name="id10" class="reference">Other Validator Usage</a></li>
<li><a href="#state" id="id11" name="id11" class="reference">State</a></li>
<li><a href="#invalid-exceptions" id="id12" name="id12" class="reference">Invalid Exceptions</a></li>
<li><a href="#messages-language-customization" id="id13" name="id13" class="reference">Messages, Language Customization</a></li>
<li><a href="#http-html-form-input" id="id14" name="id14" class="reference">HTTP/HTML Form Input</a></li>
</ul>
</li>
</ul>
</div>
<div class="section">
<h1><a href="#id5" id="introduction" name="introduction" class="toc-backref">Introduction</a></h1>
<p>Validation (which encompasses conversion as well) is the core function
of FormEncode.  FormEncode really tries to <em>encode</em> the values from
one source into another (hence the name).  So a Python structure can
be encoded in a series of HTML fields (a flat dictionary of strings).
A HTML form submission can in turn be turned into a the original
Python structure.</p>
</div>
<div class="section">
<h1><a href="#id6" id="using-validation" name="using-validation" class="toc-backref">Using Validation</a></h1>
<p>In FormEncode validation and conversion happen simultaneously.
Frequently you cannot convert a value without ensuring its validity,
and validation problems can occur in the middle of conversion.</p>
<p>The basic metaphor for validation is <strong>to_python</strong> and
<strong>from_python</strong>.  In this context "Python" is meant to refer to "here"
-- the trusted application, your own Python objects.  The "other" may
be a web form, an external database, an XML-RPC request, or any data
source that is not completely trusted or does not map directly to
Python's object model.  <tt class="docutils literal"><span class="pre">to_python</span></tt> is the process of taking
external data and preparing it for internal use, <tt class="docutils literal"><span class="pre">from_python</span></tt>
generally reverses this process (<tt class="docutils literal"><span class="pre">from_python</span></tt> is usually the less
interesting of the pair, but provides some important features).</p>
<p>The core of this validation process is two methods and an exception:</p>
<pre class="literal-block">&gt;&gt;&gt; import formencode
&gt;&gt;&gt; from formencode import validators
&gt;&gt;&gt; validator = validators.Int()
&gt;&gt;&gt; validator.to_python("10")
10
&gt;&gt;&gt; validator.to_python("ten")
Traceback (most recent call last):
    ...
Invalid: Please enter an integer value
</pre>
<p><tt class="docutils literal"><span class="pre">"ten"</span></tt> isn't a valid integer, so we get a <tt class="docutils literal"><span class="pre">formencode.Invalid</span></tt>
exception.  Typically we'd catch that exception, and use it for some
sort of feedback.  Like:</p>
<!-- comment (fake raw_input):

>>> raw_input_input = []
>>> def raw_input(prompt):
...     value = raw_input_input.pop(0)
...     print '%s%s' % (prompt, value)
...     return value
>>> raw_input_input.extend(['ten', '10'])
>>> raw_input_input.extend(['bob', '[email protected]']) -->
<pre class="literal-block">&gt;&gt;&gt; def get_integer():
...     while 1:
...         try:
...             value = raw_input('Enter a number: ')
...             return validator.to_python(value)
...         except formencode.Invalid, e:
...             print e
...
&gt;&gt;&gt; get_integer()
Enter a number: ten
Please enter an integer value
Enter a number: 10
10
</pre>
<p>We can also generalize this kind of function:</p>
<pre class="literal-block">&gt;&gt;&gt; def valid_input(prompt, validator):
...     while 1:
...         try:
...             value = raw_input(prompt)
...             return validator.to_python(value)
...         except formencode.Invalid, e:
...             print e
&gt;&gt;&gt; valid_input('Enter your email: ', validators.Email())
Enter your email: bob
An email address must contain a single @
Enter your email: [email protected]
'[email protected]'
</pre>
<p><tt class="docutils literal"><span class="pre">Invalid</span></tt> exceptions generally give a good, user-readable error
message about the problem with the input.  Using the exception gets
more complicated when you use compound data structures (dictionaries
and lists), which we'll talk about <a href="#compound-validators" class="reference">later</a>.</p>
<p>We'll talk more about these individual validators later, but first
we'll talk about more complex validation than just integers or
individual values.</p>
<div class="section">
<h2><a href="#id7" id="available-validators" name="available-validators" class="toc-backref"><span id="schemas"></span>Available Validators</a></h2>
<p>There's lots of validators.  The best way to read about the individual
validators available in the <tt class="docutils literal"><span class="pre">formencode.validators</span></tt> module is to
read the <a href="http://formencode.org/module-formencode.validators.html#classes" class="reference">validators generated documentation</a>.</p>
</div>
<div class="section">
<h2><a href="#id8" id="compound-validators" name="compound-validators" class="toc-backref">Compound Validators</a></h2>
<p>While validating single values is useful, it's only a <em>little</em> useful.
Much more interesting is validating a set of values.  This is called a
<em>Schema</em>.</p>
<p>For instance, imagine a registration form for a website.  It takes the
following fields, with restrictions:</p>
<ul class="simple">
<li><tt class="docutils literal"><span class="pre">first_name</span></tt> (not empty)</li>
<li><tt class="docutils literal"><span class="pre">last_name</span></tt> (not empty)</li>
<li><tt class="docutils literal"><span class="pre">email</span></tt> (not empty, valid email)</li>
<li><tt class="docutils literal"><span class="pre">username</span></tt> (not empty, unique)</li>
<li><tt class="docutils literal"><span class="pre">password</span></tt> (reasonably secure)</li>
<li><tt class="docutils literal"><span class="pre">password_confirm</span></tt> (matches password)</li>
</ul>
<p>There's a couple validators that aren't part of FormEncode, because
they'll be specific to your application:</p>
<pre class="literal-block">&gt;&gt;&gt; # We don't really have a database of users, so we'll fake it:
&gt;&gt;&gt; usernames = []
&gt;&gt;&gt; class UniqueUsername(formencode.FancyValidator):
...     def _to_python(self, value, state):
...         if value in usernames:
...             raise formencode.Invalid(
...                 'That username already exists',
...                 value, state)
...         return value
</pre>
<div class="note">
<p class="first admonition-title">Note</p>
<p class="last"><a href="http://formencode.org/class-formencode.api.FancyValidator.html" class="reference">formencode.FancyValidator</a> is the superclass for
most validators in FormEncode, and it provides a number of useful
features that most validators can use -- for instance, you can pass
<tt class="docutils literal"><span class="pre">strip=True</span></tt> into any of these validators, and they'll strip
whitespace from the incoming value before any other validation.</p>
</div>
<p>This overrides <tt class="docutils literal"><span class="pre">_to_python</span></tt>: <tt class="docutils literal"><span class="pre">formencode.FancyValidator</span></tt> adds a
number of extra features, and then calls the private <tt class="docutils literal"><span class="pre">_to_python</span></tt>
method, which is the method you'll typically write.  When a validator
finds an error it raises an exception (<a href="http://formencode.org/class-formencode.api.Invalid.html" class="reference">formencode.Invalid</a>), with the error message and the
value and "state" objects.  We'll talk about <a href="#state" class="reference">state</a> later.  Here's the
other custom validator, that checks passwords against words in the
standard Unix word file:</p>
<pre class="literal-block">&gt;&gt;&gt; class SecurePassword(formencode.FancyValidator):
...     words_filename = '/usr/share/dict/words'
...     def _to_python(self, value, state):
...         f = open(self.words_filename)
...         lower = value.strip().lower()
...         for line in f:
...             if line.strip().lower() == lower:
...                 raise formencode.Invalid(
...                     'Please do not base your password on a '
...                     'dictionary term', value, state)
...         return value
</pre>
<p>And here's a schema:</p>
<pre class="literal-block">&gt;&gt;&gt; class Registration(formencode.Schema):
...     first_name = validators.String(not_empty=True)
...     last_name = validators.String(not_empty=True)
...     email = validators.Email(resolve_domain=True)
...     username = formencode.All(validators.PlainText(),
...                               UniqueUsername())
...     password = SecurePassword()
...     password_confirm = validators.String()
...     chained_validators = [validators.FieldsMatch(
...         'password', 'password_confirm')]
</pre>
<p>Like any other validator, a <tt class="docutils literal"><span class="pre">Registration</span></tt> instance will have the
<tt class="docutils literal"><span class="pre">to_python</span></tt> and <tt class="docutils literal"><span class="pre">from_python</span></tt> methods.  The input should be a
dictionary, with keys like <tt class="docutils literal"><span class="pre">"first_name"</span></tt>, <tt class="docutils literal"><span class="pre">"password"</span></tt>, etc.  The
validators you give as attributes will be applied to each of the
values of the dictionary.  <em>All</em> the values will be validated, so if
there are multiple invalid fields you will get information about all
of them.</p>
<p>Most validators (anything that subclasses
<tt class="docutils literal"><span class="pre">formencode.FancyValidator</span></tt>) will take a certain standard set of
constructor keyword arguments.  See <a href="http://formencode.org/class-formencode.api.FancyValidator.html" class="reference">FancyValidator</a> for more -- here we use
<tt class="docutils literal"><span class="pre">not_empty=True</span></tt>.</p>
<p>Another notable validator is <a href="http://formencode.org/class-formencode.compound.All.html" class="reference">All</a> -- this is a <em>compound
validator</em> -- that is, it's a validator that takes validators as
input.  Schemas are one example; in this case <tt class="docutils literal"><span class="pre">All</span></tt> takes a list of
validators and applies each of them in turn.  <a href="http://formencode.org/class-formencode.compound.Any.html" class="reference">Any</a> is its compliment, that uses
the first passing validator in its list.</p>
<p id="chained-validators"><span id="pre-validators"></span><tt class="docutils literal"><span class="pre">chained_validators</span></tt> are validators that are run on the entire
dictionary after other validation is done (<tt class="docutils literal"><span class="pre">pre_validators</span></tt> are
applied before the schema validation).  You could actually achieve the
same thing by using <tt class="docutils literal"><span class="pre">All</span></tt> with the schema validators (<a href="http://formencode.org/class-formencode.validators.FieldsMatch.html" class="reference">FieldsMatch</a> is just another
validator that can be applied to dictionaries).  In this case
<tt class="docutils literal"><span class="pre">validators.FieldsMatch</span></tt> checks that the value of the two fields are
the same (i.e., that the password matches the confirmation).</p>
<p>Since a <a href="http://formencode.org/class-formencode.schema.Schema.html" class="reference">Schema</a> is just
another kind of validator, you can nest these indefinitely, validating
dictionaries of dictionaries.</p>
<p id="foreach">You can also validate lists of items using <a href="http://formencode.org/class-formencode.foreach.ForEach.html" class="reference">ForEach</a>.  For example, let's say we
have a form where someone can edit a list of book titles.  Each title
has an associated book ID, so we can match up the new title and the
book it is for:</p>
<pre class="literal-block">&gt;&gt;&gt; class BookSchema(formencode.Schema):
...     id = validators.Int()
...     title = validators.String(not_empty=True)
&gt;&gt;&gt; validator = formencode.ForEach(BookSchema())
</pre>
<p>The <tt class="docutils literal"><span class="pre">validator</span></tt> we've created will take a list of dictionaries as
input (like <tt class="docutils literal"><span class="pre">[{"id":</span> <span class="pre">"1",</span> <span class="pre">"title":</span> <span class="pre">"War</span> <span class="pre">&amp;</span> <span class="pre">Peace"},</span> <span class="pre">{"id":</span> <span class="pre">"2",</span>
<span class="pre">"title":</span> <span class="pre">"Brave</span> <span class="pre">New</span> <span class="pre">World"},</span> <span class="pre">...]</span></tt>).  It applies the <tt class="docutils literal"><span class="pre">BookSchema</span></tt>
to each entry, and collects any errors and reraises them.  Of course,
when you are validating input from an HTML form you won't get well
structured data like this (we'll talk about that <a href="#http-html-form-input" class="reference">later</a>).</p>
</div>
<div class="section">
<h2><a href="#id9" id="writing-your-own-validator" name="writing-your-own-validator" class="toc-backref">Writing Your Own Validator</a></h2>
<p>We gave a brief introduction to creating a validator earlier
(<tt class="docutils literal"><span class="pre">UniqueUsername</span></tt> and <tt class="docutils literal"><span class="pre">SecurePassword</span></tt>).  We'll discuss that a
little more.  Here's a more complete implementation of
<tt class="docutils literal"><span class="pre">SecurePassword</span></tt>:</p>
<pre class="literal-block">&gt;&gt;&gt; import re
&gt;&gt;&gt; class SecurePassword(validators.FancyValidator):
...
...     min = 3
...     non_letter = 1
...     letter_regex = re.compile(r'[a-zA-Z]')
...
...     messages = {
...         'too_few': 'Your password must be longer than %(min)i '
...                   'characters long',
...         'non_letter': 'You must include at least %(non_letter)i '
...                      'characters in your password',
...         }
...
...     def _to_python(self, value, state):
...         # _to_python gets run before validate_python.  Here we
...         # strip whitespace off the password, because leading and
...         # trailing whitespace in a password is too elite.
...         return value.strip()
...
...     def validate_python(self, value, state):
...         if len(value) &lt; self.min:
...             raise Invalid(self.message("too_few", state,
...                                        min=self.min),
...                           value, state)
...         non_letters = self.letter_regex.sub('', value)
...         if len(non_letters) &lt; self.non_letter:
...             raise Invalid(self.message("non_letter",
...                                         non_letter=self.non_letter),
...                           value, state)
</pre>
<p>With all validators, any arguments you pass to the constructor will be
used to set instance variables.  So <tt class="docutils literal"><span class="pre">SecureValidator(min=5)</span></tt> will be
a minimum-five-character validator.  This makes it easy to also
subclass other validators, giving different default values.</p>
<p>Unlike the previous implementation we use <tt class="docutils literal"><span class="pre">validate_python</span></tt> (which
is another method <tt class="docutils literal"><span class="pre">FancyValidator</span></tt> allows us to use).
<tt class="docutils literal"><span class="pre">validate_python</span></tt> doesn't have any return value, it simply raises an
exception if it needs to.  It validates the value <em>after</em> it has been
converted (by <tt class="docutils literal"><span class="pre">_to_python</span></tt>).  <tt class="docutils literal"><span class="pre">validate_other</span></tt> validates before
conversion, but that's usually not that useful.</p>
<p>The use of <tt class="docutils literal"><span class="pre">self.message(...)</span></tt> is meant to make the messages easy to
format for different environments, and replacable (with translations,
or simply with different text).  Each message should have an
identifier (<tt class="docutils literal"><span class="pre">"min"</span></tt> and <tt class="docutils literal"><span class="pre">"non_letter"</span></tt> in this example).  The
keyword arguments to <tt class="docutils literal"><span class="pre">message</span></tt> are used for message substitution.
See <a href="#messages" class="reference">Messages</a> for more.</p>
</div>
<div class="section">
<h2><a href="#id10" id="other-validator-usage" name="other-validator-usage" class="toc-backref">Other Validator Usage</a></h2>
<p>Validators use instance variables to store their customization
information.  You can use either subclassing or normal instantiation
to set these.  These are (effectively) equivalent:</p>
<pre class="literal-block">&gt;&gt;&gt; plain = validators.Regex(regex='^[a-zA-Z]+$')
&gt;&gt;&gt; # and...
&gt;&gt;&gt; class Plain(validators.Regex):
...     regex = '^[a-zA-Z]+$'
&gt;&gt;&gt; plain = Plain()
</pre>
<p>You can actually use classes most places where you could use an
instance; <tt class="docutils literal"><span class="pre">.to_python()</span></tt> and <tt class="docutils literal"><span class="pre">.from_python()</span></tt> will create
instances as necessary, and many other methods are available on both
the instance and the class level.</p>
<p>When dealing with nested validators this class syntax is often easier
to work with, and better displays the structure.</p>
<p id="fancyvalidator">There are several options that most validators support (including your
own validators, if you subclass from <a href="http://formencode.org/class-formencode.api.FancyValidator.html" class="reference">FancyValidator</a>):</p>
<dl class="docutils">
<dt><tt class="docutils literal"><span class="pre">if_empty</span></tt>:</dt>
<dd>If set, then this value will be returned if the input evaluates
to false (empty list, empty string, None, etc), but not the 0 or
False objects.  This only applies to <tt class="docutils literal"><span class="pre">.to_python()</span></tt>.</dd>
<dt><tt class="docutils literal"><span class="pre">not_empty</span></tt>:</dt>
<dd>If true, then if an empty value is given raise an error.
(Both with <tt class="docutils literal"><span class="pre">.to_python()</span></tt> and also <tt class="docutils literal"><span class="pre">.from_python()</span></tt>
if <tt class="docutils literal"><span class="pre">.validate_python</span></tt> is true).</dd>
<dt><tt class="docutils literal"><span class="pre">strip</span></tt>:</dt>
<dd>If true and the input is a string, strip it (occurs before empty
tests).</dd>
<dt><tt class="docutils literal"><span class="pre">if_invalid</span></tt>:</dt>
<dd>If set, then when this validator would raise Invalid during
<tt class="docutils literal"><span class="pre">.to_python()</span></tt>, instead return this value.</dd>
<dt><tt class="docutils literal"><span class="pre">if_invalid_python</span></tt>:</dt>
<dd>If set, when the Python value (converted with
<tt class="docutils literal"><span class="pre">.from_python()</span></tt>) is invalid, this value will be returned.</dd>
<dt><tt class="docutils literal"><span class="pre">accept_python</span></tt>:</dt>
<dd>If True (the default), then <tt class="docutils literal"><span class="pre">.validate_python()</span></tt> and
<tt class="docutils literal"><span class="pre">.validate_other()</span></tt> will not be called when
<tt class="docutils literal"><span class="pre">.from_python()</span></tt> is used.</dd>
<dt><tt class="docutils literal"><span class="pre">if_missing</span></tt>:</dt>
<dd>Typically when a field is missing the schema will raise an
error.  In that case no validation is run -- so things like
<tt class="docutils literal"><span class="pre">if_invalid</span></tt> won't be triggered.  This special attribute (if
set) will be used when the field is missing, and no error will
occur.  (<tt class="docutils literal"><span class="pre">None</span></tt> or <tt class="docutils literal"><span class="pre">()</span></tt> are common values)</dd>
</dl>
</div>
<div class="section">
<h2><a href="#id11" id="state" name="state" class="toc-backref">State</a></h2>
<p>All the validators receive a magic, somewhat meaningless <tt class="docutils literal"><span class="pre">state</span></tt>
argument (which defaults to <tt class="docutils literal"><span class="pre">None</span></tt>).  It's used for very little in
the validation system as distributed, but is primarily intended to be
an object you can use to hook your validator into the context of the
larger system.</p>
<p>For instance, imagine a validator that checks that a user is permitted
access to some resource.  How will the validator know which user is
logged in?  State!  Imagine you are localizing it, how will the
validator know the locale?  State!  Whatever else you need to pass in,
just put it in the state object as an attribute, then look for that
attribute in your validator.</p>
<p>Also, during compound validation (a <a href="http://formencode.org/class-formencode.schema.Schema.html" class="reference">Schema</a> or <a href="http://formencode.org/class-formencode.foreach.ForEach.html" class="reference">ForEach</a>) the state (if not None)
will have more instance variables added to it.  During a <tt class="docutils literal"><span class="pre">Schema</span></tt>
(dictionary) validation the instance variable <tt class="docutils literal"><span class="pre">key</span></tt> and
<tt class="docutils literal"><span class="pre">full_dict</span></tt> will be added -- <tt class="docutils literal"><span class="pre">key</span></tt> is the current key (i.e.,
validator name), and <tt class="docutils literal"><span class="pre">full_dict</span></tt> is the rest of the values being
validated.  During a <tt class="docutils literal"><span class="pre">ForEeach</span></tt> (list) validation, <tt class="docutils literal"><span class="pre">index</span></tt> and
<tt class="docutils literal"><span class="pre">full_list</span></tt> will be set.</p>
</div>
<div class="section">
<h2><a href="#id12" id="invalid-exceptions" name="invalid-exceptions" class="toc-backref">Invalid Exceptions</a></h2>
<p>Besides the string error message, <a href="http://formencode.org/class-formencode.api.Invalid.html" class="reference">Invalid</a> exceptions have a few other
instance variables:</p>
<dl class="docutils">
<dt><tt class="docutils literal"><span class="pre">value</span></tt>:</dt>
<dd>The input to the validator that failed.</dd>
<dt><tt class="docutils literal"><span class="pre">state</span></tt>:</dt>
<dd>The associated <a href="#state" class="reference">state</a>.</dd>
<dt><tt class="docutils literal"><span class="pre">msg</span></tt>:</dt>
<dd>The error message (<tt class="docutils literal"><span class="pre">str(exc)</span></tt> returns this)</dd>
<dt><tt class="docutils literal"><span class="pre">error_list</span></tt>:</dt>
<dd>If the exception happened in a <tt class="docutils literal"><span class="pre">ForEach</span></tt> (list) validator, then
this will contain a list of <tt class="docutils literal"><span class="pre">Invalid</span></tt> exceptions.  Each item
from the list will have an entry, either None for no error, or an
exception.</dd>
<dt><tt class="docutils literal"><span class="pre">error_dict</span></tt>:</dt>
<dd>If the exception happened in a <tt class="docutils literal"><span class="pre">Schema</span></tt> (dictionary) validator,
then this will contain <tt class="docutils literal"><span class="pre">Invalid</span></tt> exceptions for each failing
field.  Passing fields not be included in this dictionary.</dd>
<dt><tt class="docutils literal"><span class="pre">.unpack_errors()</span></tt>:</dt>
<dd>This method returns a set of lists and dictionaries containing
strings, for each error.  It's an unpacking of <tt class="docutils literal"><span class="pre">error_list</span></tt>,
<tt class="docutils literal"><span class="pre">error_dict</span></tt> and <tt class="docutils literal"><span class="pre">msg</span></tt>.  If you get an Invalid exception from
a <tt class="docutils literal"><span class="pre">Schema</span></tt>, you probably want to call this method on the
exception object.</dd>
</dl>
</div>
<div class="section">
<h2><a href="#id13" id="messages-language-customization" name="messages-language-customization" class="toc-backref"><span id="messages"></span>Messages Customization</a></h2>
<p>All of the error messages can be customized.  Each error message has a
key associated with it, like <tt class="docutils literal"><span class="pre">"too_few"</span></tt> in the registration
example.  You can overwrite these messages by using you own <tt class="docutils literal"><span class="pre">messages</span>
<span class="pre">=</span> <span class="pre">{"key":</span> <span class="pre">"text"}</span></tt> in the class statement, or as an argument when you
call a class.  Either way, you do not lose messages that you do not
define, you only overwrite ones that you specify.</p>
<p>Messages often take arguments, like the number of characters, the
invalid portion of the field, etc.  These are always substituted as a
dictionary (by name).  So you will use placeholders like <tt class="docutils literal"><span class="pre">%(key)s</span></tt>
for each substitution.  This way you can reorder or even ignore
placeholders in your new message.</p>
<p>When you are creating a validator, for maximum flexibility you should
use the <tt class="docutils literal"><span class="pre">message</span></tt> function, like:</p>
<pre class="literal-block">messages = {
    'key': 'my message (with a %(substitution)s)',
    }

def validate_python(self, value, state):
    raise Invalid(self.message('key', substitution='apples'),
                  value, state)
</pre>
</div>

<div id ="added by GH">
<h2>Localisation of error messages (i18n)</h2>

When a failed validation accurs FormEncode tries to output the error message in the appropirate language.
For this it uses the standard  <a href="http://docs.python.org/lib/module-gettext.html">gettext mechansim of python</a>. To translate the message in the appropirate message FE has to find a gettext function that translates the string. The language  to be translated into and the used domain is determined by the found gettext function.
To serve a standard translation mechanism and to enable custom translations it looks in the following order to find a gettext ("_") function:

<ol>
<li>method of the state object
<li>function of __builtin__<br>
This function is only used when:
<pre class="literal-block">
Validator.use_builtin_gettext == True #True is default
</pre>

<li>formencode builtin _stdtrans function 
<p>
for standalone use of FormEncode. The language to use is determined out of the local system (see <a href="http://docs.python.org/lib/node733.html"> gettext documentation)</a>. Optionally you can also set the language or the domain explicitly with the function:
</p>
<pre class="literal-block">
formencode.api.set_stdtranslation(domain="FormEncode", languages=["de"])
</pre>
Formencode comes with a Domain "FormeEncode" and the corresponding messages in the directory:
<pre class="literal-block">
localedir/language/LC_MESSAGES/FormEncode.mo
</pre>
</ol>

<h3>Custom gettext function and addtional parameters</h3>

If you use a custom gettext function and you want formencode to call your function with additional parameters you can set the dictionary:

<pre class="literal-block">
Validators.gettextargs
</pre>


<h3>Available languages:</h3>

All available languages are part of the code as a whole. You can see the currently available languages in the source under the directory:
<pre class="literal-block">
formencode/i18n
</pre>

If your's is not present yet, please consider contributing a translation:

<ol>
<li>svn co http://svn.formencode.org/FormEncode/trunk/
<li>cd formencode/i18n
<li>mkdir <lang>/LC_MESSAGES
<li>cp FormEncode.pot <lang>/LC_MESSAGES/FormEncode.po
<li>emacs <lang>/LC_MESSAGES/FormEncode.po # or whatever editor you prefer
<li>#make the translation
<li>msgfmt.py <lang>/LC_MESSAGES/FormEncode.po
<li>TEST
<li>send the PO and MO files to: g...-LfrpOBifzZo+ytmZ3SK/[email protected]
DONE

</ol>

see also http://docs.python.org/lib/node738.html

Optionally you can also add a test of your language to tests/test_i18n.py:

Example of a language test:
<pre class="literal-block">
ne = formencode.validators.NotEmpty()
[...]
def test_de():
  _test_lang("de", u"Bitte einen Wert eingeben")

</pre>

add the test for your language:

<pre class="literal-block">
def test_&lt;lang&gt;():
  _test_lang("&lt;lang&gt;", u"&lt;translation of Not Empty Text in the language
&lt;lang&gt;") 

</pre>


</div>



<div class="section">
<h2><a href="#id14" id="http-html-form-input" name="http-html-form-input" class="toc-backref">HTTP/HTML Form Input</a></h2>
<p>The validation expects nested data structures; specifically <a href="http://formencode.org/class-formencode.schema.Schema.html" class="reference">Schema</a> and <a href="http://formencode.org/class-formencode.foreach.ForEach.html" class="reference">ForEach</a> deal with these structures
well.  HTML forms, however, do not produce nested structures -- they
produce flat structures with keys (input names) and associated values.</p>
<p>Validator includes the module <cite>variabledecode
&lt;module-formencode.variabledecode.html&gt;</cite>, which allows you to encode
nested dictionary and list structures into a flat dictionary.</p>
<p>To do this it uses keys with <tt class="docutils literal"><span class="pre">"."</span></tt> for nested dictionaries, and
<tt class="docutils literal"><span class="pre">"-int"</span></tt> for (ordered) lists.  So something like:</p>
<table class="docutils" border="1">
<colgroup>
<col width="50%">
<col width="50%">
</colgroup>
<thead valign="bottom">
<tr><th class="head">key</th>
<th class="head">value</th>
</tr>
</thead>
<tbody valign="top">
<tr><td>names-1.fname</td>
<td>John</td>
</tr>
<tr><td>names-1.lname</td>
<td>Doe</td>
</tr>
<tr><td>names-2.fname</td>
<td>Jane</td>
</tr>
<tr><td>names-2.lname</td>
<td>Brown</td>
</tr>
<tr><td>names-3</td>
<td>Tim Smith</td>
</tr>
<tr><td>action</td>
<td>save</td>
</tr>
<tr><td>action.option</td>
<td>overwrite</td>
</tr>
<tr><td>action.confirm</td>
<td>yes</td>
</tr>
</tbody>
</table>
<p>Will be mapped to:</p>
<pre class="literal-block">{'names': [{'fname': "John", 'lname': "Doe"},
           {'fname': "Jane", 'lname': 'Brown'},
           "Tim Smith"],
 'action': {None: "save",
            'option': "overwrite",
            'confirm': "yes"},
}
</pre>
<p>In other words, <tt class="docutils literal"><span class="pre">'a.b'</span></tt> creates a dictionary in <tt class="docutils literal"><span class="pre">'a'</span></tt>, with
<tt class="docutils literal"><span class="pre">'b'</span></tt> as a key (and if <tt class="docutils literal"><span class="pre">'a'</span></tt> already had a value, then that value
is associated with the key <tt class="docutils literal"><span class="pre">None</span></tt>).  Lists are created with keys
with <tt class="docutils literal"><span class="pre">'-int'</span></tt>, where they are ordered by the integer (the integers
are used for sorting, missing numbers in a sequence are ignored).</p>
<p><a href="http://formencode.org/class-formencode.variabledecode.NestedVariables.html" class="reference">NestedVariables</a> is a
validator that decodes and encodes dictionaries using this algorithm.
You can use it with a Schema's <a href="#pre-validators" class="reference">pre_validators</a> attribute.</p>
<p>Of course, in the example we use the data is rather eclectic -- for
instance, Tim Smith doesn't have his name separated into first and
last.  Validators work best when you keep lists homogeneous.  Also, it
is hard to access the <tt class="docutils literal"><span class="pre">'action'</span></tt> key in the example; storing the
options (action.option and action.confirm) under another key would be
preferable.</p>
</div>
</div>

</div></div>
      
      <div id="footer">
        
        
        <p style="float: left;">
          
          built with 
          <a href="http://lesscode.org/projects/pudge/">pudge/0.1.3</a> |
		      original design by 
          <a href="http://blog.ratterobert.com/">ratter / robert</a>
	  
	      </p>
        <div>
        <br> <!--
        <a name="search">
          <form method="get" id="searchform" 
                action="http://lesscode.org/blog/index.php">
            <div>
              <input type="text" value="" name="s" id="s" />
              <input type="submit" id="searchsubmit" value="Search" />
            </div>
          </form>
        </a> -->
        <br>
        </div>
      </div>
    </div>
  </body></html>
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.