Code

Ticket #1566: validators.diff

File validators.diff, 2.6 KB (added by gary.wilson@…, 8 years ago)
Line 
1Index: core/validators.py
2===================================================================
3--- core/validators.py  (revision 2598)
4+++ core/validators.py  (working copy)
5@@ -382,14 +382,19 @@
6         if not self.regexp.search(field_data):
7             raise ValidationError(self.error_message)
8 
9-class AnyValidator:
10+class SomeValidators:
11+
12+    """Validates if `num_required` of given validators pass.
13+   
14+    This validator tries all given validators in order.  Once the
15+    `num_required` number of validators pass, validation passes without
16+    any further testing.  If `num_required` is not met, a validation error
17+    is raised with the given message.  The message is rather unspecific,
18+    so it's best to specify one on instantiation.
19     """
20-    This validator tries all given validators. If any one of them succeeds,
21-    validation passes. If none of them succeeds, the given message is thrown
22-    as a validation error. The message is rather unspecific, so it's best to
23-    specify one on instantiation.
24-    """
25-    def __init__(self, validator_list=[], error_message=gettext_lazy("This field is invalid.")):
26+
27+    def __init__(self, num_required, validator_list=[], error_message=gettext_lazy("This field is invalid.")):
28+        self.num_required = num_required
29         self.validator_list = validator_list
30         self.error_message = error_message
31         for v in validator_list:
32@@ -397,14 +402,31 @@
33                 self.always_test = True
34 
35     def __call__(self, field_data, all_data):
36+        validated_count = 0
37         for v in self.validator_list:
38             try:
39                 v(field_data, all_data)
40-                return
41             except ValidationError, e:
42                 pass
43+            else:
44+                validated_count += 1
45+                if validated_count >= self.num_required:
46+                    return
47         raise ValidationError(self.error_message)
48 
49+class AnyValidator(SomeValidators):
50+
51+    """Validates if any one of the given validators pass.
52+   
53+    This validator tries all given validators in order.  Once a validator
54+    succeeds, validation passes.  If none of them succeed, a validation
55+    error is raised with the given message.  The message is rather
56+    unspecific, so it's best to specify one on instantiation.
57+    """
58+
59+    def __init__(self, num_required=1, validator_list=[], error_message=gettext_lazy("This field is invalid.")):
60+        SomeValidators.__init__(self, num_required, validator_list=validator_list, error_message=error_message)
61+
62 class URLMimeTypeCheck:
63     "Checks that the provided URL points to a document with a listed mime type"
64     class CouldNotRetrieve(ValidationError):