15
qr-code

FormEncode: (1) Introduction

FormEncode is very helpful to validate forms data. Here is a very simple example to show how to use it.

Suppose we have a form in our mako template as follows:

  <form id="formExample" method="post" action="${c.url.to.action}">
  <table>
    <tr>
      <td><input type="text" id="firstID" name="number1" value=""/></td>
      <td><input type="text" id="secondID" name="int1" value=""/></td>
      <td><input type="text" id="thirdID" name="string1" value=""/></td>
    </tr>
  </table>
</form>

To validate these three input fields, we need to define a class like this:

import formencode
from formencode import validators

class myFormValidation(formencode.Schema):
    number1 = validators.Number(min=0, max=100, not_empty=False)
    int1 = validators.Int(min=30, max=100)
    string1 = validators.String(max=128, strip=True)

As we can see from the above example, formencode matches each input via the name attribute within a tag. In the controller, we'll validate all parameters from the above form.

def example_action(self, **kwargs):
    """Demo action to show how formencode works."""

    example_form = myFormValidation(request.params)
Posted on .
blog comments powered by Disqus