The validators module is accessible via the formencode module.
This is raised in response to invalid input. It has several public attributes:
This class contains 2 members.
Confirms that the input/output is of the proper type.
Uses the parameters:
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
This class contains 22 members.
The base class of most validators. See IValidator for more, and FancyValidator for the more common (and more featureful) class.
Messages
This class contains 14 members.
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')
Traceback (most recent call last):
...
Invalid: invalid literal for int(): a
Messages
This class contains 22 members.
FancyValidator is the (abstract) superclass for various validators and converters. A subclass can validate, convert, or do both. There is no formal distinction made here.
Validators have two important external methods:
There are five important methods for subclasses to override, however none of these have to be overridden, only the ones that are appropriate for the validator:
Validators should have no internal state besides the values given at instantiation. They should be reusable and reentrant.
All subclasses can take the arguments/instance variables:
Messages
This class contains 17 members.
This converter converts everything to the same thing.
I.e., you pass in the constant value when initializing, then all values get converted to that constant value.
This is only really useful for funny situations, like:
fromEmailValidator = ValidateAny(
ValidEmailAddress(),
Constant('unknown@localhost'))
In this case, the if the email is not valid 'unknown@localhost' will be used instead. Of course, you could use if_invalid instead.
Examples:
>>> Constant('X').to_python('y')
'X'
Messages
This class contains 17 members.
Invalid if the value is longer than maxLength . Uses len(), so it can work for strings, lists, or anything with length.
Examples:
>>> max5 = MaxLength(5)
>>> max5.to_python('12345')
'12345'
>>> max5.from_python('12345')
'12345'
>>> max5.to_python('123456')
Traceback (most recent call last):
...
Invalid: Enter a value less than 5 characters long
>>> max5(accept_python=False).from_python('123456')
Traceback (most recent call last):
...
Invalid: Enter a value less than 5 characters long
>>> max5.to_python([1, 2, 3])
[1, 2, 3]
>>> max5.to_python([1, 2, 3, 4, 5, 6])
Traceback (most recent call last):
...
Invalid: Enter a value less than 5 characters long
>>> max5.to_python(5)
Traceback (most recent call last):
...
Invalid: Invalid value (value with length expected)
Messages
This class contains 18 members.
Invalid if the value is shorter than minlength . Uses len(), so it can work for strings, lists, or anything with length.
Examples:
>>> min5 = MinLength(5)
>>> min5.to_python('12345')
'12345'
>>> min5.from_python('12345')
'12345'
>>> min5.to_python('1234')
Traceback (most recent call last):
...
Invalid: Enter a value at least 5 characters long
>>> min5(accept_python=False).from_python('1234')
Traceback (most recent call last):
...
Invalid: Enter a value at least 5 characters long
>>> min5.to_python([1, 2, 3, 4, 5])
[1, 2, 3, 4, 5]
>>> min5.to_python([1, 2, 3])
Traceback (most recent call last):
...
Invalid: Enter a value at least 5 characters long
>>> min5.to_python(5)
Traceback (most recent call last):
...
Invalid: Invalid value (value with length expected)
Messages
This class contains 18 members.
Invalid if value is empty (empty string, empty list, etc).
Generally for objects that Python considers false, except zero which is not considered invalid.
Examples:
>>> ne = NotEmpty(messages={'empty': 'enter something'})
>>> ne.to_python('')
Traceback (most recent call last):
...
Invalid: enter something
>>> ne.to_python(0)
0
Messages
This class contains 18 members.
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
This class contains 18 members.
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
This class contains 20 members.
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
This class contains 20 members.
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
This class contains 21 members.
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
This class contains 19 members.
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
This class contains 18 members.
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
This class contains 23 members.
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
This class contains 19 members.
Convert a value to an integer.
Example:
>>> Int.to_python('10')
10
>>> Int.to_python('ten')
Traceback (most recent call last):
...
Invalid: Please enter an integer value
Messages
This class contains 20 members.
Convert a value to a float or integer. Tries to convert it to an integer if no information is lost.
>>> Number.to_python('10')
10
>>> Number.to_python('10.5')
10.5
>>> Number.to_python('ten')
Traceback (most recent call last):
...
Invalid: Please enter a number
Messages
This class contains 17 members.
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
This class contains 23 members.
Converts things to unicode string, this is a specialization of the String class.
In addition to the String arguments, an encoding argument is also accepted. By default the encoding will be utf-8.
All converted strings are returned as Unicode strings.
>>> UnicodeString().to_python(None)
u''
>>> UnicodeString().to_python([])
u''
>>> UnicodeString(encoding='utf-7').to_python('Ni Ni Ni')
u'Ni Ni Ni'
Messages
This class contains 23 members.
This is for when you think you may return multiple values for a certain field.
This way the result will always be a list, even if there's only one result. It's equivalent to ForEach(convertToList=True).
If you give use_set=True, then it will return an actual sets.Set object.
>>> Set.to_python(None)
[]
>>> Set.to_python('this')
['this']
>>> Set.to_python(('this', 'that'))
['this', 'that']
>>> s = Set(use_set=True)
>>> s.to_python(None)
Set([])
>>> s.to_python('this')
Set(['this'])
>>> s.to_python(('this',))
Set(['this'])
Messages
This class contains 20 members.
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.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('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 = Email(not_empty=False)
>>> e.to_python('')
Messages
This class contains 21 members.
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/bar.html')
'http://hahaha/bar.html'
>>> u.to_python('https://test.com')
'https://test.com'
>>> u = URL(add_http=False, check_exists=True)
>>> u.to_python('http://google.com')
'http://google.com'
>>> u.to_python('http://colorstudy.com/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.exists.formencode.org/test.html')
Traceback (most recent call last):
...
Invalid: An error occured when trying to connect to the server: ...
Messages
This class contains 21 members.
Valid state or province code (two-letter).
Well, for now I don't know the province codes, but it does state codes. Give your own states list to validate other state-like codes; give extra_states to add values without losing the current state values.
>>> s = StateProvince('XX')
>>> s.to_python('IL')
'IL'
>>> s.to_python('XX')
'XX'
>>> s.to_python('xx')
'XX'
>>> s.to_python('YY')
Traceback (most recent call last):
...
Invalid: That is not a valid state code
Messages
This class contains 20 members.
Validates, and converts to ###-###-####, optionally with extension (as ext.##...). Only support US phone numbers. See InternationalPhoneNumber for support for that kind of phone number.
>>> p = PhoneNumber()
>>> p.to_python('333-3333')
Traceback (most recent call last):
...
Invalid: Please enter a number, with area code, in the form ###-###-####, optionally with "ext.####"
>>> p.to_python('555-555-5555')
'555-555-5555'
>>> p.to_python('1-393-555-3939')
'1-393-555-3939'
>>> p.to_python('321.555.4949')
'321.555.4949'
>>> p.to_python('3335550000')
'3335550000'
Messages
This class contains 17 members.
Validates, and converts phone numbers to +##-###-#######. Adapted from RFC 3966
>>> p = IPhoneNumberValidator(default_cc=49)
>>> p.to_python('333-3333')
Traceback (most recent call last):
...
Invalid: Please enter a number, with area code, in the form +##-###-#######.
>>> p.to_python('0555/4860-300')
'+49-555-4860-300'
>>> p.to_python('0555-49924-51')
'+49-555-49924-51'
>>> p.to_python('0555/8114100')
'+49-555-8114100'
>>> p.to_python('0555 8114100')
'+49-555-8114100'
>>> p.to_python(' +49 (0)555 350 60 0')
'+49-555-35060-0'
>>> p.to_python('+49 555 350600')
'+49-555-350600'
>>> p.to_python('0049/ 555/ 871 82 96')
'+49-555-87182-96'
>>> p.to_python('0555-2 50-30')
'+49-555-250-30'
>>> p.to_python('(05 55)4 94 33 47')
'+49-555-49433-47'
>>> p.to_python('+973-555431')
'+973-555431'
>>> p.to_python('1-393-555-3939')
'+1-393-555-3939'
>>> p.to_python('+43 (1) 55528/0')
'+43-1-55528-0'
>>> p.to_python('+43 5555 429 62-0')
'+43-5555-42962-0'
>>> p.to_python('00 218 55 33 50 317 321')
'+218-55-3350317-321'
>>> p.to_python('+218 (0)55-3636639/38')
'+218-55-3636639-38'
Messages
This class contains 18 members.
Converts a cgi.FieldStorage instance to a value that FormEncode can use for file uploads.
Messages
This class contains 17 members.
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
This class contains 20 members.
Validates and converts a string date, like mm/yy, dd/mm/yy, dd-mm-yy, etc. Using month_style you can support 'mm/dd/yyyy' or 'dd/mm/yyyy'. Only these two general styles are supported.
Accepts English month names, also abbreviated. Returns value as a datetime object (you can get mx.DateTime objects if you use datetime_module='mxDateTime'). Two year dates are assumed to be within 1950-2020, with dates from 21-49 being ambiguous and signaling an error.
Use accept_day=False if you just want a month/year (like for a credit card expiration date).
>>> d = DateConverter()
>>> d.to_python('12/3/09')
datetime.date(2009, 12, 3)
>>> d.to_python('12/3/2009')
datetime.date(2009, 12, 3)
>>> d.to_python('2/30/04')
Traceback (most recent call last):
...
Invalid: That month only has 29 days
>>> d.to_python('13/2/05')
Traceback (most recent call last):
...
Invalid: Please enter a month from 1 to 12
Messages
This class contains 26 members.
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
This class contains 22 members.
US Postal codes (aka Zip Codes).
>>> PostalCode.to_python('55555')
'55555'
>>> PostalCode.to_python('55555-5555')
'55555-5555'
>>> PostalCode.to_python('5555')
Traceback (most recent call last):
...
Invalid: Please enter a zip code (5 digits)
Messages
This class contains 20 members.
Take a field from a dictionary, removing the key from the dictionary.
name is the key. The field value and a new copy of the dictionary with that field removed are returned.
>>> StripField('test').to_python({'a': 1, 'test': 2})
(2, {'a': 1})
>>> StripField('test').to_python({})
Traceback (most recent call last):
...
Invalid: The name 'test' is missing
Messages
This class contains 18 members.
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
This class contains 19 members.
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
This class contains 19 members.
Encodes a string into a signed string, and base64 encodes both the signature string and a random nonce.
It is up to you to provide a secret, and to keep the secret handy and consistent.
Messages
This class contains 21 members.
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
This class contains 18 members.
Formencode validator to check whether a string is a correct hardware (MAC) address.
Examples:
>>> mac = MACAddress()
>>> mac.to_python('aa:bb:cc:dd:ee:ff')
'aabbccddeeff'
>>> mac.to_python('aa:bb:cc:dd:ee:ff:e')
Traceback (most recent call last):
...
Invalid: A MAC address must contain 12 digits and A-F; the value you gave has 13 characters
>>> mac.to_python('aa:bb:cc:dd:ee:fx')
Traceback (most recent call last):
...
Invalid: MAC addresses may only contain 0-9 and A-F (and optionally :), not 'x'
>>> MACAddress(add_colons=True).to_python('aabbccddeeff')
'aa:bb:cc:dd:ee:ff'
Messages
This class contains 19 members.
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
This class contains 20 members.
Messages
This class contains 23 members.
Messages
This class contains 23 members.
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
This class contains 24 members.
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
Messages
This class contains 24 members.
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
This class contains 25 members.
Checks that credit card security code has the correct number of digits for the given credit card type.
You pass in the name of the field that has the credit card type and the field with the credit card security code.
>>> code = CreditCardSecurityCode()
>>> code.to_python({'ccType': 'visa', 'ccCode': '111'})
{'ccType': 'visa', 'ccCode': '111'}
>>> code.to_python({'ccType': 'visa', 'ccCode': '1111'})
Traceback (most recent call last):
...
Invalid: ccCode: Invalid credit card security code length
Messages
This class contains 24 members.
See the source for more information.