3 from tw.forms import validators
5 from bluechips import model
6 from bluechips.model import meta
8 from bluechips.model.types import Currency
10 class UserSelect(forms.SingleSelectField):
13 for u in meta.Session.query(model.User):
17 validator = validators.Wrapper(
18 to_python=(lambda x: meta.Session.query(model.User).get(int(x))),
19 from_python=(lambda x: str(x.id)))
21 def _is_option_selected(self, option_value, value):
23 return option_value == value.id
27 class AmountField(forms.TextField):
29 validator = validators.All(
31 to_python=(lambda x: Currency(float(x) * 100)),
32 from_python=Currency.__str_no_dollar__),
33 validators.Regex(r'^\-?[0-9]*(\.[0-9]{2})?$'))
35 # This is virtually copied from formencode.validator.FieldsMatch, but
36 # I wanted my own version for fields that shouldn't match
37 class FieldsDontMatch(validators.FormValidator):
39 Tests that the given fields do not match.
44 valid_partial_form = True
45 __unpackargs__ = ('*', 'field_names')
48 'invalid': "Fields match"
51 def validate_partial(self, field_dict, state):
52 for name in self.field_names:
53 if not field_dict.has_key(name):
55 self.validate_python(field_dict, state)
57 def validate_python(self, field_dict, state):
59 for ref_index, ref in enumerate(self.field_names):
60 for name in self.field_names[ref_index+1:]:
61 if field_dict.get(name, '') == field_dict.get(ref, ''):
62 errors[name] = self.message('invalid', state)
64 error_list = errors.items()
66 error_message = '<br>\n'.join(
67 ['%s: %s' % (name, value) for name, value in error_list])
68 raise validators.Invalid(error_message,
72 __all__ = ['UserSelect', 'AmountField', 'FieldsDontMatch']