Introduction
FormHandler() Class
The FormHandler() class acts like a dictionary, but with extra functionality. This class is used by instantiating it, then optionally calling validators on it's fields, and finally using the data in the field.
Unlike the standard Python form handler, the values associated with the keys in the dictionary are actual values, and do not need to have their "value" method called to get to the submitted data.
from jotweb.input import SimpleForm form = SimpleForm.FormHandler() # validate fields if form.vdt_required('EmailAddr'): form.vdt_emailaddr('EmailAddr') if form.vdt_required('FullName'): form.vdt_realname('FullName' form.vdt_length('FullName', 3, 20) print 'Subscribing user "%(FullName)s with address %(EmailAddr)s' % form
Note that if the above is placed in a "formhandler.py" file, elements of the form can be accessed from TAL/HTML with a path like "formhandler/form/EmailAddr", and error checking from the HTML can be done with the path "formhandler/form/geterrors".
SimpleForm.FormHandler(dataIn = None)
Arguments:
- dataIn (optional) -- (Dictionary) If passed in, this will specify form data to use.
Description: This call instantiates a FormHandler object, using either the form filled data passed by the client, or using the dictionary passed in via the "dataIn" argument.
Note that if dataIn is not passed, this call will consume the form data submitted by the user. Multiple calls without dataIn set will produce the same results, because a local copy of the consumed form is kept. Calling something else which consumes the form will not work.
FormHandler Methods
ValidatorClear()
Arguments: None
Returns: None
Description: This function can be used to clear any errors in the validator, for example if a new set of validations should be done on the same form.
geterrors()
Returns: None if no errors were encountered, otherwise a list of the error messages.
Description: Fairly self-explanitory from Returns field.
FormHandler Validator and Conversion Methods
These methods are used for validating form fields. They take an optional "msg" argument which can be used to override the default message relating to form validation failure. These strings may include several "%(keys)s" strings, which will be replaced by appropriate values in the form validation step. As noted in the specific validator description, some validators augment this information. All validators provide the following keys:
- %(field)s -- The name of the field that is being validated.
- %(value)s -- The value of the field being validated.
- %(why)s -- (Where noted below) Some validators do multiple checks. For these, a "why" is set, which provides more details on why the validation failed.
The conversion methods are:
cvt_makelowercase(field, msg = None)
Returns: Always succeeds.
Side-effects: Converts field to lowercase.
Description: Converts the letters in the field to lower-case.
cvt_makeuppercase(field, msg = None)
Returns: Always succeeds.
Side-effects: Converts field to uppercase.
Description: Converts the letters in the field to upper-case.
The validator methods are:
vdt_addmessage(fieldIn, msgIn)
Arguments:
- fieldIn -- (String) Name of offending field.
- msgIn -- (String) Validation error message to add.
Returns: 0.
Side-effects: Adds message to validators error list.
Description: Allows the developer to add a custom error message to the validator list (to handle any validation problems not handled by the other functions).
vdt_alnum(field, msg = None)
Returns: 0 if validation failed, 1 if it succeeded.
Side-effects: Adds message to validators error list on failure.
Description: Does the field contain only characters and digits?
vdt_alpha(field, msg = None)
Returns: 0 if validation failed, 1 if it succeeded.
Side-effects: Adds message to validators error list on failure.
Description: Does the field contain only characters?
vdt_ccnumber(field, msg = None)
Returns: 0 if validation failed, 1 if it succeeded.
Side-effects: Adds message to validators error list on failure.
msg Strings: This validator also sets "%(why)s", as mentioned at the top of this section.
Description: Checks that the field contains only digits and the characters space and hyphen. Then runs a credit card number check algorithm against the card number, to ensure that it does not have any transposed digits and is otherwise a valid number. Note that this does not check with any merchant banks and therefore the number may not actually have an account associated with it.
This is a front-line check on the card number, and would typically be used with card processing system to actually run charges against accounts.
vdt_emailaddr(field, msg = None)
Returns: 0 if validation failed, 1 if it succeeded.
Side-effects: Adds message to validators error list on failure.
Description: Checks for a valid e-mail address. The regex used is: "^[-0-9a-zA-Z._+]+@[-0-9a-zA-Z.]+\.[-0-9a-zA-Z.]+$". Note that underscores may be used in the username, but are invalid in domain names. The right hand side must have at least one dot. This does not support source routed addresses (%) or bang paths (!).
vdt_fieldequals(field, field2, msg = None)
Returns: 0 if validation failed, 1 if it succeeded.
Side-effects: Adds message to validators error list on failure.
msg Strings: This validator also sets "%(field2)s" to the name of the field2 field and "%(value2)s" to the value of field2.
Description: Checks that the indicated fields have the same value. Useful for checking that two passowrd fields match.
vdt_integer(field, msg = None)
Returns: 0 if validation failed, 1 if it succeeded.
Side-effects: Adds message to validators error list on failure. Converts field to an integer type.
Description: Check for a valid integer. Allows a leading minus sign (-) for negative numbers. use the intvalue for checking for only positive integers.
If the field is a valid integer, the form field is converted into an integer.
vdt_intvalue(field, min = None, max = None, msg = None)
Returns: 0 if validation failed, 1 if it succeeded.
Side-effects: Adds message to validators error list on failure. Converts field to an integer type.
msg Strings: This validator also sets "%(why)s", as mentioned at the top of this section.
Description: Like "vdt_integer", but optionally checks the minimum and maximum values. If "min" is passed, it specifies the smallest value which this field can be. Similarly, "max" specifies the largest allowed value.
If the field is a valid integer, the form field is converted into an integer.
vdt_ipv4addr(field, msg = None)
Returns: 0 if validation failed, 1 if it succeeded.
Side-effects: Adds message to validators error list on failure.
msg Strings: This validator also sets "%(why)s", as mentioned at the top of this section.
Description: Check for a valid IPv4 address. The regex used is "^(\d+)\.(\d+)\.(\d+)\.(\d+)$". Obviously, this precludes shortened addresses, such as "127.1". As of June, 2003, many systems seem to be rejecting these abbreviated addresses.
vdt_length(field, max = None, min = None, msg = None)
Returns: 0 if validation failed, 1 if it succeeded.
Side-effects: Adds message to validators error list on failure.
msg Strings: This validator also sets "%(why)s", as mentioned at the top of this section.
Description: Check the length of data in the field. If "min" is not None, it specifies the minimum number of characters allowed in this field. Likewise, "max" specifies the maximum length.
Note that if used on an integer field, this should be called before the validators that convert to integer.
vdt_lengthlist(field, lengthlist, msg = None)
Returns: 0 if validation failed, 1 if it succeeded.
Side-effects: Adds message to validators error list on failure.
msg Strings: This validator also sets "%(lengthlist)s", which is a string containing a human-readable version of the lengthlist argument.
Description: Check that the length of the field is one of the ones specified in the lengthlist list. For example, if a field must either be empty or contain 8 characters (for an optional zip-code, for example), pass a lengthlist argument of "(0, 8)".
Note that if used on an integer field, this should be called before the validators that convert to integer.
vdt_login(field, msg = None)
Returns: 0 if validation failed, 1 if it succeeded.
Side-effects: Adds message to validators error list on failure. Converts field to lower-case.
msg Strings: This validator also sets "%(why)s", as mentioned at the top of this section.
Description: Checks for unix-like login names. These names must consist of only letters and digits, and must have at least one non-digit.
vdt_multientry(field, msg = None)
Returns: 0 if validation failed, 1 if it succeeded.
Description: Returns true if the form field has multiple entries.
vdt_numeric(field, msg = None)
Returns: 0 if validation failed, 1 if it succeeded.
Side-effects: Adds message to validators error list on failure.
Description: Does the field contain only digits? This is different from the "vdt_integer()" validator in that this does not convert the field to an integer, and allows for an empty field.
vdt_password(field, msg = None)
Returns: 0 if validation failed, 1 if it succeeded.
Side-effects: Adds message to validators error list on failure.
Description: Checks for valid password strings. This is similar to "vdt_unsafepassword()", but includes fewer shell and SQL special characters and is therefore safer if your code will be passing data to shell commands.
The "vdt_unsafepassword()" validator has fewer limits on special characters.
vdt_realname(field, msg = None)
Returns: 0 if validation failed, 1 if it succeeded.
Side-effects: Adds message to validators error list on failure.
Description: Something that looks like a person's name. The regex used is "[-a-zA-Z0-9.'"_,()]+$", allowing characters and digits, and the characters ``-.'"_,()''.
vdt_regex(field, regex, msg = None)
Returns: 0 if validation failed, 1 if it succeeded.
Side-effects: Adds message to validators error list on failure.
Description: Match the field against a regular expression using the Python "re.match()" call.
vdt_required(field, msg = None)
Returns: 0 if validation failed, 1 if it succeeded.
Side-effects: Adds message to validators error list on failure.
Description: Checks to see if the form has the specified field and that it is not blank.
vdt_singleentry(field, msg = None)
Returns: 0 if validation failed, 1 if it succeeded.
Description: Returns false if the form field has multiple entries.
vdt_unsafepassword(field, msg = None)
Returns: 0 if validation failed, 1 if it succeeded.
Side-effects: Adds message to validators error list on failure.
Description: Checks for valid password strings. This is probably the most permissive regex here, and does include some potentially unsafe characters such as * and &. It does not include either single or double quotes or the grave accent.
vdt_validchars(field, validChars, msg = None)
Returns: 0 if validation failed, 1 if it succeeded.
Side-effects: Adds message to validators error list on failure.
msg Strings: This validator also sets "%(invalidchars)s", which is the list of characters in the field which are invalid.
Description: Check the field for characters not in the regular expression in "validChars". Any character not mentioned in that regular expression is listed in "%(invalidchars)s", which may be used in the "msg" string (in addition to the ones listed at the beginning of this section of the documentation).
Example
Simple Form
Create a file called "simpleform.html", which contains the form HTML:
<form action="simplepost.html" method="POST">
Email Address: <input type="text" name="EmailAddr" /><br />
Full Name: <input type="text" name="FullName" /><br />
<input type="submit" name="subscribe" value="Subscribe" /><br />
</form>Create a file called "simplepost.html", which contains the HTML which validates and displays the results of the form:
<div tal:define="form formchk/form">
<div tal:condition="not:form/geterrors">
<!-- Form is valid -->
<h1><font color="#00ff00">Form Success</font></h1>
Full Name: <span tal:replace="form/FullName">Full Name</span><br />
Email Addr: <span tal:replace="form/EmailAddr">Full Name</span><br />
</div>
<div tal:condition="form/geterrors">
<!-- Form had validation errors -->
<h1><font color="#ff0000">Form Errors</font></h1>
<p />The following errors were found in your form input:
<ul>
<li tal:repeat="value form/geterrors" tal:content="value">Error</li>
</ul>
</div>
</div>Finally, set up the form validator as the file "formchk.py":
from jotweb.input import SimpleForm
form = SimpleForm.FormHandler()
if form.vdt_required('EmailAddr'):
form.vdt_emailaddr('EmailAddr')
if form.vdt_required('FullName'):
form.vdt_realname('FullName')
form.vdt_length('FullName', 3, 20)See Examples
JOTWeb includes a number of examples, one of which is a slightly complicated form handling routine using SimpleForm(). Please see the "examples" directory in your JOTWeb installation, in particular the "form.html" and "formpy.py" files. This example is similar to the above, but slightly more complicated.