Validating user input¶
The code in this section is the complete listing of a Reahl web application which demonstrates the validation of a single item that can be input by a user.
The application will render a sole text input on its home page:
The user is expected to type a valid email address into the input. When the user types something into the input and hits tab (for example), the typed input is checked and a useful error message is shown:
The error message changes while the user types. For example, if the user deletes the invalid email address, the message changes:
When the input is changed to a valid value, the message disappears:
Here is a listing of the code, followed by an explanation:
from __future__ import print_function, unicode_literals, absolute_import, division from reahl.web.fw import UserInterface from reahl.web.ui import TwoColumnPage, Form, TextInput from reahl.component.modelinterface import exposed, EmailField class ValidationUI(UserInterface): def assemble(self): self.define_view('/', title='Validation demo', page=HomePage.factory()) class HomePage(TwoColumnPage): def __init__(self, view): super(HomePage, self).__init__(view, style='basic') self.main.add_child(CommentForm(view)) class Comment(object): @exposed def fields(self, fields): fields.email_address = EmailField(label='Email address', required=True) class CommentForm(Form): def __init__(self, view): super(CommentForm, self).__init__(view, 'myform') comment = Comment() self.add_child( TextInput(self, comment.fields.email_address) )
This application models the concept of a Comment, which is meant to represent a comment which can be left by a user. The idea is that users can leave comments, but have to “sign” each comment using their email address.
Comment is said to @expose certain Fields which are used to receive input from a user. In this case, a Comment has an email_address attribute, exposed via an EmailField.
In the code for the CommentForm (the very last line) a TextInput Widget is connected to the email_address field of a particular Comment. This EmailField is responsible for validating user input.