]> asedeno.scripts.mit.edu Git - bluechips.git/commitdiff
Add a FieldsDontMatch validator
authorEvan Broder <broder@mit.edu>
Wed, 16 Jul 2008 04:28:39 +0000 (04:28 +0000)
committerEvan Broder <broder@mit.edu>
Wed, 16 Jul 2008 04:28:39 +0000 (04:28 +0000)
bluechips/widgets/__init__.py

index 8c25e78c37af0f2794228388d0487317af341fd0..9da303d68945c5bcc028b140d8ec49a426651e81 100644 (file)
@@ -5,6 +5,8 @@ from tw.forms import validators
 from bluechips import model
 from bluechips.model import meta
 
+from bluechips.lib.base import _
+
 from decimal import Decimal
 
 class UserSelect(forms.SingleSelectField):
@@ -19,7 +21,10 @@ class UserSelect(forms.SingleSelectField):
         from_python=(lambda x: str(x.id)))
     
     def _is_option_selected(self, option_value, value):
-        return option_value == value.id
+        if value is not None:
+            return option_value == value.id
+        else:
+            return False
 
 class AmountField(forms.TextField):
     size = 8
@@ -29,4 +34,41 @@ class AmountField(forms.TextField):
             from_python=str),
         validators.Regex(r'^[0-9]*(\.[0-9]{2})?$', not_empty=True))
 
-__all__ = ['UserSelect', 'AmountField']
+# This is virtually copied from formencode.validator.FieldsMatch, but
+# I wanted my own version for fields that shouldn't match
+class FieldsDontMatch(validators.FormValidator):
+    """
+    Tests that the given fields do not match.
+    """
+    
+    show_match = False
+    field_names = None
+    valid_partial_form = True
+    __unpackargs__ = ('*', 'field_names')
+    
+    messages = {
+        'invalid': _("Fields match")
+        }
+    
+    def validate_partial(self, field_dict, state):
+        for name in self.field_names:
+            if not field_dict.has_key(name):
+                return
+        self.validate_python(field_dict, state)
+    
+    def validate_python(self, field_dict, state):
+        errors = {}
+        for ref_index, ref in enumerate(self.field_names):
+            for name in self.field_names[ref_index+1:]:
+                if field_dict.get(name, '') == field_dict.get(ref, ''):
+                    errors[name] = self.message('invalid', state)
+        if errors:
+            error_list = errors.items()
+            error_list.sort()
+            error_message = '<br>\n'.join(
+                ['%s: %s' % (name, value) for name, value in error_list])
+            raise validators.Invalid(error_message,
+                                     field_dict, state,
+                                     error_dict=errors)
+
+__all__ = ['UserSelect', 'AmountField', 'FieldsDontMatch']