Skip to content

Commit bef3468

Browse files
Snilemansam
authored andcommitted
adds Or and And validator
1 parent 247f99c commit bef3468

File tree

1 file changed

+53
-1
lines changed

1 file changed

+53
-1
lines changed

validator/__init__.py

Lines changed: 53 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -460,6 +460,58 @@ def __call__(self, value, dictionary):
460460
dependent = self.then_clause(dictionary)
461461
return conditional, dependent
462462

463+
class Or(Validator):
464+
"""
465+
For Or logic verification
466+
467+
# Example:
468+
validations = {
469+
"foo": [Or(Equals(1), Blank())]
470+
}
471+
passes = {"foo": 1}
472+
also_passes = {"foo":''}
473+
fails = {"foo":"x",}
474+
"""
475+
def __init__(self, *validators):
476+
self.validators = validators
477+
self.err_message = "must validate in {0}".format([item.err_message for item in validators])
478+
self.not_message = "must not validate in {0}".format([item.not_message for item in validators])
479+
480+
def __call__(self, field):
481+
for validator in self.validators:
482+
if validator(field):
483+
return True
484+
return False
485+
486+
class And(Validator):
487+
"""
488+
For And logic verification
489+
490+
Although a field itself supports
491+
multiple authentication conditions,
492+
it is not supported in the Or validator.
493+
494+
# Example:
495+
validations = {
496+
"foo": [Or(And(Url(), Length(14)),Blank())]
497+
}
498+
passes = {"foo": "http://vk.com"}
499+
also_passes = {"foo":''}
500+
fails = {"foo":"x",}
501+
also_fails = {"foo":"http://github.com"}
502+
"""
503+
def __init__(self, *validators):
504+
self.validators = validators
505+
self.err_message = "must validate all {0}".format([item.err_message for item in validators])
506+
self.not_message = "must not validate all {0}".format([item.not_message for item in validators])
507+
508+
def __call__(self, field):
509+
for validator in self.validators:
510+
if not validator(field):
511+
# self.err_message = validator.err_message
512+
return False
513+
return True
514+
463515
class Length(Validator):
464516
"""
465517
Use to specify that the
@@ -730,4 +782,4 @@ def _validate_list_helper(validation, dictionary, key, errors):
730782
errors[key].append(dependent[1])
731783
# handling for normal validators
732784
else:
733-
_validate_and_store_errs(v, dictionary, key, errors)
785+
_validate_and_store_errs(v, dictionary, key, errors)

0 commit comments

Comments
 (0)