Hello,
I want a custom validator which, amongst other things, translates
alpha characters to upper case. I want a partly validated value to be
displayed back in the form, but in its uppercased form, when
validation fails.
I am using the usual:
if form.accepts(request.vars, session):
response.flash = 'form accepted'
elif form.errors:
response.flash = 'Please correct the errors in the form'
else:
response.flash = 'Please fill out the application'
return dict(form=form)
processing of the form - an SQLFORM as it happens.
Here is my validator which I have shamelessly copied from django:
# uk postcode validator
class IS_UK_POSTCODE(object):
import re
outcode_pattern = '[A-PR-UWYZ]([0-9]{1,2}|([A-HIK-Y][0-9](|[0-9]|
[ABEHMNPRVWXY]))|[0-9][A-HJKSTUW])'
incode_pattern = '[0-9][ABD-HJLNP-UW-Z]{2}'
postcode_regex = re.compile(r'^(GIR 0AA|%s %s)$' %
(outcode_pattern, incode_pattern))
space_regex = re.compile(r' *(%s)$' % incode_pattern)
def __init__(self, error_message='Must be valid UK postcode'):
self.error_message = error_message
def __call__(self, value):
postcode = value.upper().strip()
# Put a single space before the incode (second part).
postcode = self.space_regex.sub(r' \1', postcode)
if not self.postcode_regex.search(postcode):
return postcode, self.error_message
else:
return postcode, None
As you can see I don't return the input value, I return the uppercased
value (value.upper().strip()). However I can't get that uppercased
fragment back into the form.
When I run my controller, and type a partial postcode (e.g. 'se1') in
the field in lower case, I correctly get a validation error, and the
incorrect partial postcode is displayed back in the form. I want to
have the uppercased partial value displayed ('SE1'). I have tried, in
my elif form.errors: branch, to change form.vars.postcode to the
uppercased value. I have also tried return dict(form=form,
form.vars.postcode=value) where value is my uppcased fragment. None of
these work. Is there an easy way?
Thanks for any assistance.