Icon Header

tw.forms.validators

exception tw.forms.validators.Invalid

This is raised in response to invalid input. It has several public attributes:

msg:
The message, without values substituted. For instance, if you want HTML quoting of values, you can apply that.
substituteArgs:
The arguments (a dictionary) to go with msg.
str(self):
The message describing the error, with values substituted.
value:
The offending (invalid) value.
state:
The state that went with this validator. This is an application-specific object.
error_list:
If this was a compound validator that takes a repeating value, and sub-validator(s) had errors, then this is a list of those exceptions. The list will be the same length as the number of values – valid values will have None instead of an exception.
error_dict:
Like error_list, but for dictionary compound validators.
unpack_errors(encode_variables=False, dict_char='.', list_char='-')

Returns the error as a simple data structure – lists, dictionaries, and strings.

If encode_variables is true, then this will return a flat dictionary, encoded with variable_encode

class tw.forms.validators.Regex(*args, **kw)

Invalid if the value doesn’t match the regular expression regex.

The regular expression can be a compiled re object, or a string which will be compiled for you.

Use strip=True if you want to strip the value before validation, and as a form of conversion (often useful).

Examples:

>>> cap = Regex(r'^[A-Z]+$')
>>> cap.to_python('ABC')
'ABC'

Note that .from_python() calls (in general) do not validate the input:

>>> cap.from_python('abc')
'abc'
>>> cap(accept_python=False).from_python('abc')
Traceback (most recent call last):
  ...
Invalid: The input is not valid
>>> cap.to_python(1)
Traceback (most recent call last):
  ...
Invalid: The input must be a string (not a <type 'int'>: 1)
>>> Regex(r'^[A-Z]+$', strip=True).to_python('  ABC  ')
'ABC'
>>> Regex(r'this', regexOps=('I',)).to_python('THIS')
'THIS'

Messages

badType:
The input must be a string (not a %(type)s: %(value)r)
empty:
Please enter a value
invalid:
The input is not valid
noneType:
The input must be a string (not None)
class tw.forms.validators.OneOf(*args, **kw)

Tests that the value is one of the members of a given list.

If testValueList=True, then if the input value is a list or tuple, all the members of the sequence will be checked (i.e., the input must be a subset of the allowed values).

Use hideList=True to keep the list of valid values out of the error message in exceptions.

Examples:

>>> oneof = OneOf([1, 2, 3])
>>> oneof.to_python(1)
1
>>> oneof.to_python(4)
Traceback (most recent call last):
  ...
Invalid: Value must be one of: 1; 2; 3 (not 4)
>>> oneof(testValueList=True).to_python([2, 3, [1, 2, 3]])
[2, 3, [1, 2, 3]]
>>> oneof.to_python([2, 3, [1, 2, 3]])
Traceback (most recent call last):
  ...
Invalid: Value must be one of: 1; 2; 3 (not [2, 3, [1, 2, 3]])

Messages

badType:
The input must be a string (not a %(type)s: %(value)r)
empty:
Please enter a value
invalid:
Invalid value
noneType:
The input must be a string (not None)
notIn:
Value must be one of: %(items)s (not %(value)r)
class tw.forms.validators.TimeConverter(*args, **kw)

Converts times in the format HH:MM:SSampm to (h, m, s). Seconds are optional.

For ampm, set use_ampm = True. For seconds, use_seconds = True. Use ‘optional’ for either of these to make them optional.

Examples:

>>> tim = TimeConverter()
>>> tim.to_python('8:30')
(8, 30)
>>> tim.to_python('20:30')
(20, 30)
>>> tim.to_python('30:00')
Traceback (most recent call last):
    ...
Invalid: You must enter an hour in the range 0-23
>>> tim.to_python('13:00pm')
Traceback (most recent call last):
    ...
Invalid: You must enter an hour in the range 1-12
>>> tim.to_python('12:-1')
Traceback (most recent call last):
    ...
Invalid: You must enter a minute in the range 0-59
>>> tim.to_python('12:02pm')
(12, 2)
>>> tim.to_python('12:02am')
(0, 2)
>>> tim.to_python('1:00PM')
(13, 0)
>>> tim.from_python((13, 0))
'13:00:00'
>>> tim2 = tim(use_ampm=True, use_seconds=False)
>>> tim2.from_python((13, 0))
'1:00pm'
>>> tim2.from_python((0, 0))
'12:00am'
>>> tim2.from_python((12, 0))
'12:00pm'

Examples with datetime.time:

>>> v = TimeConverter(use_datetime=True)
>>> a = v.to_python('18:00')
>>> a
datetime.time(18, 0)
>>> b = v.to_python('30:00')
Traceback (most recent call last):
    ...
Invalid: You must enter an hour in the range 0-23
>>> v2 = TimeConverter(prefer_ampm=True, use_datetime=True)
>>> v2.from_python(a)
'6:00:00pm'
>>> v3 = TimeConverter(prefer_ampm=True,
...                    use_seconds=False, use_datetime=True)
>>> a = v3.to_python('18:00')
>>> a
datetime.time(18, 0)
>>> v3.from_python(a)
'6:00pm'
>>> a = v3.to_python('18:00:00')
Traceback (most recent call last):
    ...
Invalid: You may not enter seconds

Messages

badHour:
You must enter an hour in the range %(range)s
badMinute:
You must enter a minute in the range 0-59
badNumber:
The %(part)s value you gave is not a number: %(number)r
badSecond:
You must enter a second in the range 0-59
badType:
The input must be a string (not a %(type)s: %(value)r)
empty:
Please enter a value
minutesRequired:
You must enter minutes (after a :)
noAMPM:
You must indicate AM or PM
noSeconds:
You may not enter seconds
noneType:
The input must be a string (not None)
secondsRequired:
You must enter seconds
tooManyColon:
There are too many :’s
class tw.forms.validators.PlainText(*args, **kw)

Test that the field contains only letters, numbers, underscore, and the hyphen. Subclasses Regex.

Examples:

>>> PlainText.to_python('_this9_')
'_this9_'
>>> PlainText.from_python('  this  ')
'  this  '
>>> PlainText(accept_python=False).from_python('  this  ')
Traceback (most recent call last):
  ...
Invalid: Enter only letters, numbers, or _ (underscore)
>>> PlainText(strip=True).to_python('  this  ')
'this'
>>> PlainText(strip=True).from_python('  this  ')
'this'

Messages

badType:
The input must be a string (not a %(type)s: %(value)r)
empty:
Please enter a value
invalid:
Enter only letters, numbers, or _ (underscore)
noneType:
The input must be a string (not None)
class tw.forms.validators.DictConverter(*args, **kw)

Converts values based on a dictionary which has values as keys for the resultant values.

If allowNull is passed, it will not balk if a false value (e.g., ‘’ or None) is given (it will return None in these cases).

to_python takes keys and gives values, from_python takes values and gives keys.

If you give hideDict=True, then the contents of the dictionary will not show up in error messages.

Examples:

>>> dc = DictConverter({1: 'one', 2: 'two'})
>>> dc.to_python(1)
'one'
>>> dc.from_python('one')
1
>>> dc.to_python(3)
Traceback (most recent call last):
Invalid: Enter a value from: 1; 2
>>> dc2 = dc(hideDict=True)
>>> dc2.hideDict
True
>>> dc2.dict
{1: 'one', 2: 'two'}
>>> dc2.to_python(3)
Traceback (most recent call last):
Invalid: Choose something
>>> dc.from_python('three')
Traceback (most recent call last):
Invalid: Nothing in my dictionary goes by the value 'three'.  Choose one of: 'one'; 'two'

Messages

badType:
The input must be a string (not a %(type)s: %(value)r)
chooseKey:
Enter a value from: %(items)s
chooseValue:
Nothing in my dictionary goes by the value %(value)s. Choose one of: %(items)s
empty:
Please enter a value
keyNotFound:
Choose something
noneType:
The input must be a string (not None)
valueNotFound:
That value is not known
class tw.forms.validators.ConfirmType(*args, **kw)

Confirms that the input/output is of the proper type.

Uses the parameters:

subclass:
The class or a tuple of classes; the item must be an instance of the class or a subclass.
type:
A type or tuple of types (or classes); the item must be of the exact class or type. Subclasses are not allowed.

Examples:

>>> cint = ConfirmType(subclass=int)
>>> cint.to_python(True)
True
>>> cint.to_python('1')
Traceback (most recent call last):
    ...
Invalid: '1' is not a subclass of <type 'int'>
>>> cintfloat = ConfirmType(subclass=(float, int))
>>> cintfloat.to_python(1.0), cintfloat.from_python(1.0)
(1.0, 1.0)
>>> cintfloat.to_python(1), cintfloat.from_python(1)
(1, 1)
>>> cintfloat.to_python(None)
Traceback (most recent call last):
    ...
Invalid: None is not a subclass of one of the types <type 'float'>, <type 'int'>
>>> cint2 = ConfirmType(type=int)
>>> cint2(accept_python=False).from_python(True)
Traceback (most recent call last):
    ...
Invalid: True must be of the type <type 'int'>

Messages

badType:
The input must be a string (not a %(type)s: %(value)r)
empty:
Please enter a value
inSubclass:
%(object)r is not a subclass of one of the types %(subclassList)s
inType:
%(object)r must be one of the types %(typeList)s
noneType:
The input must be a string (not None)
subclass:
%(object)r is not a subclass of %(subclass)s
type:
%(object)r must be of the type %(type)s
class tw.forms.validators.Bool(*args, **kw)

Always Valid, returns True or False based on the value and the existance of the value.

If you want to convert strings like 'true' to booleans, then use StringBoolean.

Examples:

>>> Bool.to_python(0)
False
>>> Bool.to_python(1)
True
>>> Bool.to_python('')
False
>>> Bool.to_python(None)
False

Messages

badType:
The input must be a string (not a %(type)s: %(value)r)
empty:
Please enter a value
noneType:
The input must be a string (not None)
class tw.forms.validators.Any(*args, **kw)
This class is like an ‘or’ operator for validators. The first validator/converter that validates the value will be used. (You can pass in lists of validators, which will be ANDed)
class tw.forms.validators.DateValidator(*args, **kw)

Validates that a date is within the given range. Be sure to call DateConverter first if you aren’t expecting mxDateTime input.

earliest_date and latest_date may be functions; if so, they will be called each time before validating.

after_now means a time after the current timestamp; note that just a few milliseconds before now is invalid! today_or_after is more permissive, and ignores hours and minutes.

Examples:

>>> from datetime import datetime, timedelta
>>> d = DateValidator(earliest_date=datetime(2003, 1, 1))
>>> d.to_python(datetime(2004, 1, 1))
datetime.datetime(2004, 1, 1, 0, 0)
>>> d.to_python(datetime(2002, 1, 1))
Traceback (most recent call last):
    ...
Invalid: Date must be after Wednesday, 01 January 2003
>>> d.to_python(datetime(2003, 1, 1))
datetime.datetime(2003, 1, 1, 0, 0)
>>> d = DateValidator(after_now=True)
>>> now = datetime.now()
>>> d.to_python(now+timedelta(seconds=5)) == now+timedelta(seconds=5)
True
>>> d.to_python(now-timedelta(days=1))
Traceback (most recent call last):
    ...
Invalid: The date must be sometime in the future
>>> d.to_python(now+timedelta(days=1)) > now
True
>>> d = DateValidator(today_or_after=True)
>>> d.to_python(now) == now
True

Messages

after:
Date must be after %(date)s
badType:
The input must be a string (not a %(type)s: %(value)r)
before:
Date must be before %(date)s
date_format:
%%A, %%d %%B %%Y
empty:
Please enter a value
future:
The date must be sometime in the future
noneType:
The input must be a string (not None)
class tw.forms.validators.Email(*args, **kw)

Validate an email address.

If you pass resolve_domain=True, then it will try to resolve the domain name to make sure it’s valid. This takes longer, of course. You must have the pyDNS modules installed to look up DNS (MX and A) records.

>>> e = Email()
>>> e.to_python(' test@foo.com ')
'test@foo.com'
>>> e.to_python('test')
Traceback (most recent call last):
    ...
Invalid: An email address must contain a single @
>>> e.to_python('test@foobar')
Traceback (most recent call last):
    ...
Invalid: The domain portion of the email address is invalid (the portion after the @: foobar)
>>> e.to_python('test@foobar.com.5')
Traceback (most recent call last):
    ...
Invalid: The domain portion of the email address is invalid (the portion after the @: foobar.com.5)
>>> e.to_python('test@foo..bar.com')
Traceback (most recent call last):
    ...
Invalid: The domain portion of the email address is invalid (the portion after the @: foo..bar.com)
>>> e.to_python('test@.foo.bar.com')
Traceback (most recent call last):
    ...
Invalid: The domain portion of the email address is invalid (the portion after the @: .foo.bar.com)
>>> e.to_python('nobody@xn--m7r7ml7t24h.com')
'nobody@xn--m7r7ml7t24h.com'
>>> e.to_python('o*reilly@test.com')
'o*reilly@test.com'
>>> e = Email(resolve_domain=True)
>>> e.resolve_domain
True
>>> e.to_python('doesnotexist@colorstudy.com')
'doesnotexist@colorstudy.com'
>>> e.to_python('test@forums.nyu.edu')
'test@forums.nyu.edu'
>>> # NOTE: If you do not have PyDNS installed this example won't work:
>>> e.to_python('test@thisdomaindoesnotexistithinkforsure.com')
Traceback (most recent call last):
    ...
Invalid: The domain of the email address does not exist (the portion after the @: thisdomaindoesnotexistithinkforsure.com)
>>> e.to_python(u'test@google.com')
u'test@google.com'
>>> e = Email(not_empty=False)
>>> e.to_python('')

Messages

badDomain:
The domain portion of the email address is invalid (the portion after the @: %(domain)s)
badType:
The input must be a string (not a %(type)s: %(value)r)
badUsername:
The username portion of the email address is invalid (the portion before the @: %(username)s)
domainDoesNotExist:
The domain of the email address does not exist (the portion after the @: %(domain)s)
empty:
Please enter an email address
noAt:
An email address must contain a single @
noneType:
The input must be a string (not None)
socketError:
An error occured when trying to connect to the server: %(error)s
class tw.forms.validators.Empty(*args, **kw)

Invalid unless the value is empty. Use cleverly, if at all.

Examples:

>>> Empty.to_python(0)
Traceback (most recent call last):
  ...
Invalid: You cannot enter a value here

Messages

badType:
The input must be a string (not a %(type)s: %(value)r)
empty:
Please enter a value
noneType:
The input must be a string (not None)
notEmpty:
You cannot enter a value here
class tw.forms.validators.Schema(*args, **kw)

A schema validates a dictionary of values, applying different validators (be key) to the different values. If allow_extra_fields=True, keys without validators will be allowed; otherwise they will raise Invalid. If filter_extra_fields is set to true, then extra fields are not passed back in the results.

Validators are associated with keys either with a class syntax, or as keyword arguments (class syntax is usually easier). Something like:

class MySchema(Schema):
    name = Validators.PlainText()
    phone = Validators.PhoneNumber()

These will not be available as actual instance variables, but will be collected in a dictionary. To remove a validator in a subclass that is present in a superclass, set it to None, like:

class MySubSchema(MySchema):
    name = None

Note that missing fields are handled at the Schema level. Missing fields can have the ‘missing’ message set to specify the error message, or if that does not exist the schema message ‘missingValue’ is used.

Messages

badDictType:
The input must be dict-like (not a %(type)s: %(value)r)
badType:
The input must be a string (not a %(type)s: %(value)r)
empty:
Please enter a value
missingValue:
Missing value
noneType:
The input must be a string (not None)
notExpected:
The input field %(name)s was not expected.
add_chained_validator
add_field
add_pre_validator
assert_dict(value, state)
Helper to assure we have proper input
subvalidators
class tw.forms.validators.FieldStorageUploadConverter(*args, **kw)

Handles cgi.FieldStorage instances that are file uploads.

This doesn’t do any conversion, but it can detect empty upload fields (which appear like normal fields, but have no filename when no upload was given).

Messages

badType:
The input must be a string (not a %(type)s: %(value)r)
empty:
Please enter a value
noneType:
The input must be a string (not None)
class tw.forms.validators.String(*args, **kw)

Converts things to string, but treats empty things as the empty string.

Also takes a max and min argument, and the string length must fall in that range.

Also you may give an encoding argument, which will encode any unicode that is found. Lists and tuples are joined with list_joiner (default ', ') in from_python.

>>> String(min=2).to_python('a')
Traceback (most recent call last):
    ...
Invalid: Enter a value 2 characters long or more
>>> String(max=10).to_python('xxxxxxxxxxx')
Traceback (most recent call last):
    ...
Invalid: Enter a value less than 10 characters long
>>> String().from_python(None)
''
>>> String().from_python([])
''
>>> String().to_python(None)
''
>>> String(min=3).to_python(None)
Traceback (most recent call last):
    ...
Invalid: Please enter a value
>>> String(min=1).to_python('')
Traceback (most recent call last):
    ...
Invalid: Please enter a value

Messages

badType:
The input must be a string (not a %(type)s: %(value)r)
empty:
Please enter a value
noneType:
The input must be a string (not None)
tooLong:
Enter a value less than %(max)i characters long
tooShort:
Enter a value %(min)i characters long or more
class tw.forms.validators.CreditCardExpires(*args, **kw)

Checks that credit card expiration date is valid relative to the current date.

You pass in the name of the field that has the credit card expiration month and the field with the credit card expiration year.

>>> ed = CreditCardExpires()
>>> ed.to_python({'ccExpiresMonth': '11', 'ccExpiresYear': '2250'})
{'ccExpiresYear': '2250', 'ccExpiresMonth': '11'}
>>> ed.to_python({'ccExpiresMonth': '10', 'ccExpiresYear': '2005'})
Traceback (most recent call last):
    ...
Invalid: ccExpiresMonth: Invalid Expiration Date<br>
ccExpiresYear: Invalid Expiration Date

Messages

badType:
The input must be a string (not a %(type)s: %(value)r)
empty:
Please enter a value
invalidNumber:
Invalid Expiration Date
noneType:
The input must be a string (not None)
notANumber:
Please enter numbers only for month and year
class tw.forms.validators.FieldsMatch(*args, **kw)

Tests that the given fields match, i.e., are identical. Useful for password+confirmation fields. Pass the list of field names in as field_names.

>>> f = FieldsMatch('pass', 'conf')
>>> f.to_python({'pass': 'xx', 'conf': 'xx'})
{'conf': 'xx', 'pass': 'xx'}
>>> f.to_python({'pass': 'xx', 'conf': 'yy'})
Traceback (most recent call last):
    ...
Invalid: conf: Fields do not match

Messages

badType:
The input must be a string (not a %(type)s: %(value)r)
empty:
Please enter a value
invalid:
Fields do not match (should be %(match)s)
invalidNoMatch:
Fields do not match
noneType:
The input must be a string (not None)
notDict:
Fields should be a dictionary
class tw.forms.validators.CreditCardValidator(*args, **kw)

Checks that credit card numbers are valid (if not real).

You pass in the name of the field that has the credit card type and the field with the credit card number. The credit card type should be one of “visa”, “mastercard”, “amex”, “dinersclub”, “discover”, “jcb”.

You must check the expiration date yourself (there is no relation between CC number/types and expiration dates).

>>> cc = CreditCardValidator()
>>> cc.to_python({'ccType': 'visa', 'ccNumber': '4111111111111111'})
{'ccNumber': '4111111111111111', 'ccType': 'visa'}
>>> cc.to_python({'ccType': 'visa', 'ccNumber': '411111111111111'})
Traceback (most recent call last):
    ...
Invalid: ccNumber: You did not enter a valid number of digits
>>> cc.to_python({'ccType': 'visa', 'ccNumber': '411111111111112'})
Traceback (most recent call last):
    ...
Invalid: ccNumber: You did not enter a valid number of digits
>>> cc().to_python({})
Traceback (most recent call last):
    ...
Invalid: The field ccType is missing

Messages

badLength:
You did not enter a valid number of digits
badType:
The input must be a string (not a %(type)s: %(value)r)
empty:
Please enter a value
invalidNumber:
That number is not valid
missing_key:
The field %(key)s is missing
noneType:
The input must be a string (not None)
notANumber:
Please enter only the number, no other characters
class tw.forms.validators.DateTimeConverter(format='%Y/%m/%d %H:%M', tzinfo=None, *args, **kwargs)

Converts Python date and datetime objects into string representation and back.

Messages

badFormat:
Invalid datetime format
badType:
The input must be a string (not a %(type)s: %(value)r)
empty:
Empty values not allowed
noneType:
The input must be a string (not None)
class tw.forms.validators.FormValidator(*args, **kw)

A FormValidator is something that can be chained with a Schema. Unlike normal chaining the FormValidator can validate forms that aren’t entirely valid.

The important method is .validate(), of course. It gets passed a dictionary of the (processed) values from the form. If you have .validate_partial_form set to True, then it will get the incomplete values as well – use .has_key() to test if the field was able to process any particular field.

Anyway, .validate() should return a string or a dictionary. If a string, it’s an error message that applies to the whole form. If not, then it should be a dictionary of fieldName: errorMessage. The special key “form” is the error message for the form as a whole (i.e., a string is equivalent to {“form”: string}).

Return None on no errors.

Messages

badType:
The input must be a string (not a %(type)s: %(value)r)
empty:
Please enter a value
noneType:
The input must be a string (not None)
class tw.forms.validators.SecureTicketValidator(widget=None, session_secret_cb=None, **kw)

Messages

badType:
The input must be a string (not a %(type)s: %(value)r)
empty:
Please enter a value
noneType:
The input must be a string (not None)
get_hash()
Generate a hash that is associated with
  • Current user
  • Current session
  • The form
class tw.forms.validators.RequireIfMissing(*args, **kw)

This requires one field based on another field being present or missing. This is applied to a form, not an individual field (usually using a Schema’s pre_validators or chained_validators).

If you provide a missing value (a string key name) then if that field is missing the field must be entered. This gives you an either/or situation.

If you provide a present value (another string key name) then if that field is present, the required field must also be present.

>>> from formencode import validators
>>> v = validators.RequireIfPresent('phone_type',
...                                 present='phone')
>>> v.to_python({'phone_type':'', 'phone':'510 420  4577'})
Traceback (most recent call last):
    ...
Invalid: You must give a value for phone_type
>>> v.to_python({'phone': ''})
{'phone': ''}

Note that if you have a validator on the optionally-required field, you should probably use if_missing=None. This way you won’t get an error from the Schema about a missing value. For example:

class PhoneInput(Schema):
    phone = PhoneNumber()
    phone_type = String(if_missing=None)
    chained_validators = [RequireifPresent('phone_type', present='phone')]

Messages

badType:
The input must be a string (not a %(type)s: %(value)r)
empty:
Please enter a value
noneType:
The input must be a string (not None)
class tw.forms.validators.FileUploadKeeper(*args, **kw)

Takes two inputs (a dictionary with keys static and upload) and converts them into one value on the Python side (a dictionary with filename and content keys). The upload takes priority over the static value. The filename may be None if it can’t be discovered.

Handles uploads of both text and cgi.FieldStorage upload values.

This is basically for use when you have an upload field, and you want to keep the upload around even if the rest of the form submission fails. When converting back to the form submission, there may be extra values 'original_filename' and 'original_content', which may want to use in your form to show the user you still have their content around.

To use this, make sure you are using variabledecode, then use something like:

<input type="file" name="myfield.upload">
<input type="hidden" name="myfield.static">

Then in your scheme:

class MyScheme(Scheme):
    myfield = FileUploadKeeper()

Note that big file uploads mean big hidden fields, and lots of bytes passed back and forth in the case of an error.

Messages

badType:
The input must be a string (not a %(type)s: %(value)r)
empty:
Please enter a value
noneType:
The input must be a string (not None)
class tw.forms.validators.OpenId(add_schema=False, **kwargs)

OpenId validator.

::
>>> v = OpenId(add_schema=True)
>>> v.to_python(' example.net ')
'http://example.net'
>>> v.to_python('@TurboGears')
'xri://@TurboGears'
>>> w = OpenId(add_schema=False)
>>> w.to_python(' example.net ')
...
Invalid: "example.net" is not a valid OpenId (it is neither an URL nor an XRI)
>>> w.to_python('!!1000')
'!!1000'
>>> w.to_python('look@me.com')
...
Invalid: "look@me.com" is not a valid OpenId (it is neither an URL nor an XRI)

Messages

badId:
%(id)s” is not a valid OpenId (it is neither an URL nor an XRI)
badType:
The input must be a string (not a %(type)s: %(value)r)
empty:
Please enter a value
noneType:
The input must be a string (not None)
class tw.forms.validators.XRI(add_xri=False, xri_type='i-name', **kwargs)

Validator for XRIs.

It supports both i-names and i-numbers, of the first version of the XRI standard.

>>> inames = XRI(xri_type="i-name")
>>> inames.to_python("   =John.Smith ")
'=John.Smith'
>>> inames.to_python("@Free.Software.Foundation")
'@Free.Software.Foundation'
>>> inames.to_python("Python.Software.Foundation")
Traceback (most recent call last):
    ...
Invalid: The type of i-name is not defined; it may be either individual or organizational
>>> inames.to_python("http://example.org")
Traceback (most recent call last):
    ...
Invalid: The type of i-name is not defined; it may be either individual or organizational
>>> inames.to_python("=!2C43.1A9F.B6F6.E8E6")
Traceback (most recent call last):
    ...
Invalid: "!2C43.1A9F.B6F6.E8E6" is an invalid i-name
>>> iname_with_schema = XRI(True, xri_type="i-name")
>>> iname_with_schema.to_python("=Richard.Stallman")
'xri://=Richard.Stallman'
>>> inames.to_python("=John Smith")
Traceback (most recent call last):
    ...
Invalid: "John Smith" is an invalid i-name
>>> inumbers = XRI(xri_type="i-number")
>>> inumbers.to_python("!!1000!de21.4536.2cb2.8074")
'!!1000!de21.4536.2cb2.8074'
>>> inumbers.to_python("@!1000.9554.fabd.129c!2847.df3c")
'@!1000.9554.fabd.129c!2847.df3c'

Messages

badIname:
%(iname)s” is an invalid i-name
badInameStart:
i-names may not start with numbers nor punctuation marks
badInumber:
%(inumber)s” is an invalid i-number
badType:
The XRI must be a string (not a %(type)s: %(value)r)
badXri:
%(xri_type)s” is not a valid type of XRI
empty:
Please enter a value
noType:
The type of i-name is not defined; it may be either individual or organizational
noneType:
The input must be a string (not None)
repeatedChar:
Dots and dashes may not be repeated consecutively
validate_python(value, state=None)

Validate an XRI

@raise Invalid: If at least one of the following conditions in met:
  • C{value} is not a string.

  • The XRI is not a personal, organizational or network one.

  • The relevant validator (i-name or i-number) considers the XRI

    is not valid.

class tw.forms.validators.RangeValidator(*args, **kw)

This is an abstract base class for Int and Number.

It verifies that a value is within range. It accepts min and max values in the constructor.

(Since this is an abstract base class, the tests are in Int and Number.)

Messages

badType:
The input must be a string (not a %(type)s: %(value)r)
empty:
Please enter a value
noneType:
The input must be a string (not None)
tooHigh:
Please enter a number that is %(max)s or smaller
tooLow:
Please enter a number that is %(min)s or greater
class tw.forms.validators.StringBool(*args, **kw)

Converts a string to a boolean.

Values like ‘true’ and ‘false’ are considered True and False, respectively; anything in true_values is true, anything in false_values is false, case-insensitive). The first item of those lists is considered the preferred form.

>>> s = StringBoolean()
>>> s.to_python('yes'), s.to_python('no')
(True, False)
>>> s.to_python(1), s.to_python('N')
(True, False)
>>> s.to_python('ye')
Traceback (most recent call last):
    ...
Invalid: Value should be 'true' or 'false'

Messages

badType:
The input must be a string (not a %(type)s: %(value)r)
empty:
Please enter a value
noneType:
The input must be a string (not None)
string:
Value should be %(true)r or %(false)r
class tw.forms.validators.StringBoolean(*args, **kw)

Converts a string to a boolean.

Values like ‘true’ and ‘false’ are considered True and False, respectively; anything in true_values is true, anything in false_values is false, case-insensitive). The first item of those lists is considered the preferred form.

>>> s = StringBoolean()
>>> s.to_python('yes'), s.to_python('no')
(True, False)
>>> s.to_python(1), s.to_python('N')
(True, False)
>>> s.to_python('ye')
Traceback (most recent call last):
    ...
Invalid: Value should be 'true' or 'false'

Messages

badType:
The input must be a string (not a %(type)s: %(value)r)
empty:
Please enter a value
noneType:
The input must be a string (not None)
string:
Value should be %(true)r or %(false)r
class tw.forms.validators.URL(*args, **kw)

Validate a URL, either http://... or https://. If check_exists is true, then we’ll actually make a request for the page.

If add_http is true, then if no scheme is present we’ll add http://

>>> u = URL(add_http=True)
>>> u.to_python('foo.com')
'http://foo.com'
>>> u.to_python('http://hahaha.ha/bar.html')
'http://hahaha.ha/bar.html'
>>> u.to_python('http://xn--m7r7ml7t24h.com')
'http://xn--m7r7ml7t24h.com'
>>> u.to_python('http://foo.com/test?bar=baz&fleem=morx')
'http://foo.com/test?bar=baz&fleem=morx'
>>> u.to_python('http://foo.com/login?came_from=http%3A%2F%2Ffoo.com%2Ftest')
'http://foo.com/login?came_from=http%3A%2F%2Ffoo.com%2Ftest'
>>> u.to_python('http://foo.com:8000/test.html')
'http://foo.com:8000/test.html'
>>> u.to_python('http://foo.com/something\nelse')
Traceback (most recent call last):
    ...
Invalid: That is not a valid URL
>>> u.to_python('https://test.com')
'https://test.com'
>>> u.to_python('http://test')
Traceback (most recent call last):
    ...
Invalid: You must provide a full domain name (like test.com)
>>> u.to_python('http://test..com')
Traceback (most recent call last):
    ...
Invalid: That is not a valid URL
>>> u = URL(add_http=False, check_exists=True)
>>> u.to_python('http://google.com')
'http://google.com'
>>> u.to_python('google.com')
Traceback (most recent call last):
    ...
Invalid: You must start your URL with http://, https://, etc
>>> u.to_python('http://ianbicking.org/doesnotexist.html')
Traceback (most recent call last):
    ...
Invalid: The server responded that the page could not be found
>>> u.to_python('http://this.domain.does.not.exist.example.org/test.html')
Traceback (most recent call last):
    ...
Invalid: An error occured when trying to connect to the server: ...

If you want to allow addresses without a TLD (e.g., localhost) you can do:

>>> URL(require_tld=False).to_python('http://localhost')
'http://localhost'

Messages

badType:
The input must be a string (not a %(type)s: %(value)r)
badURL:
That is not a valid URL
empty:
Please enter a value
httpError:
An error occurred when trying to access the URL: %(error)s
noScheme:
You must start your URL with http://, https://, etc
noTLD:
You must provide a full domain name (like %(domain)s.com)
noneType:
The input must be a string (not None)
notFound:
The server responded that the page could not be found
socketError:
An error occured when trying to connect to the server: %(error)s
status:
The server responded with a bad status code (%(status)s)
class tw.forms.validators.Pipe(*args, **kw)

This class works like ‘All’, all validators muss pass, but the result of one validation pass is handled over to the next validator. A behaviour known to Unix and GNU users as ‘pipe’.

>>> from validators import DictConverter
>>> pv = Pipe(validators=[DictConverter({1: 2}), DictConverter({2: 3}), DictConverter({3: 4})])
>>> pv.to_python(1)
4
>>> pv.to_python(1)
4
>>> pv.from_python(4)
1
>>> pv.from_python(4)
1
>>> pv.to_python(1)
4
class tw.forms.validators.IndexListConverter(*args, **kw)

Converts a index (which may be a string like ‘2’) to the value in the given list.

Examples:

>>> index = IndexListConverter(['zero', 'one', 'two'])
>>> index.to_python(0)
'zero'
>>> index.from_python('zero')
0
>>> index.to_python('1')
'one'
>>> index.to_python(5)
Traceback (most recent call last):
Invalid: Index out of range
>>> index(not_empty=True).to_python(None)
Traceback (most recent call last):
Invalid: Please enter a value
>>> index.from_python('five')
Traceback (most recent call last):
Invalid: Item 'five' was not found in the list

Messages

badType:
The input must be a string (not a %(type)s: %(value)r)
empty:
Please enter a value
integer:
Must be an integer index
noneType:
The input must be a string (not None)
notFound:
Item %(value)s was not found in the list
outOfRange:
Index out of range
class tw.forms.validators.Validator(*args, **kw)

The base class of most validators. See IValidator for more, and FancyValidator for the more common (and more featureful) class.

Messages

all_messages

Return a dictionary of all the messages of this validator, and any subvalidators if present. Keys are message names, values may be a message or list of messages. This is really just intended for documentation purposes, to show someone all the messages that a validator or compound validator (like Schemas) can produce.

@@: Should this produce a more structured set of messages, so that messages could be unpacked into a rendered form to see the placement of all the messages? Well, probably so.

from_python
message
subvalidators
Return any validators that this validator contains. This is not useful for functional, except to inspect what values are available. Specifically the .all_messages() method uses this to accumulate all possible messages.
to_python
class tw.forms.validators.Wrapper(*args, **kw)

Used to convert functions to validator/converters.

You can give a simple function for to_python, from_python, validate_python or validate_other. If that function raises an exception, the value is considered invalid. Whatever value the function returns is considered the converted value.

Unlike validators, the state argument is not used. Functions like int can be used here, that take a single argument.

Examples:

>>> def downcase(v):
...     return v.lower()
>>> wrap = Wrapper(to_python=downcase)
>>> wrap.to_python('This')
'this'
>>> wrap.from_python('This')
'This'
>>> wrap2 = Wrapper(from_python=downcase)
>>> wrap2.from_python('This')
'this'
>>> wrap2.from_python(1)
Traceback (most recent call last):
  ...
Invalid: 'int' object has no attribute 'lower'
>>> wrap3 = Wrapper(validate_python=int)
>>> wrap3.to_python('1')
'1'
>>> wrap3.to_python('a') # doctest: +ELLIPSIS
Traceback (most recent call last):
  ...
Invalid: invalid literal for int()...

Messages

badType:
The input must be a string (not a %(type)s: %(value)r)
empty:
Please enter a value
noneType:
The input must be a string (not None)
class tw.forms.validators.CIDR(*args, **kw)

Formencode validator to check whether a string is in correct CIDR notation (IP address, or IP address plus /mask)

Examples:

>>> cidr = CIDR()
>>> cidr.to_python('127.0.0.1')
'127.0.0.1'
>>> cidr.to_python('299.0.0.1')
Traceback (most recent call last):
    ...
Invalid: The octets must be within the range of 0-255 (not '299')
>>> cidr.to_python('192.168.0.1/1')
Traceback (most recent call last):
    ...
Invalid: The network size (bits) must be within the range of 8-32 (not '1')
>>> cidr.to_python('asdf')
Traceback (most recent call last):
    ...
Invalid: Please enter a valid IP address (a.b.c.d) or IP network (a.b.c.d/e)

Messages

badType:
The input must be a string (not a %(type)s: %(value)r)
bad_format:
Please enter a valid IP address (a.b.c.d) or IP network (a.b.c.d/e)