Skip to content

Commit

Permalink
OptionalIf and OptionalIfNot validators
Browse files Browse the repository at this point in the history
  • Loading branch information
jace committed Apr 8, 2015
1 parent abfe49d commit a14df9a
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
* Added ParsleyJS validation and reorganized forms to be more modular
* Added app-global CSRF protection (optional) and removed Mustache dependency
* Added ``firstline`` filter to extract first line of text from a HTML block
* ``OptionalIf`` and ``OptionalIfNot`` validators

0.3.0
-----
Expand Down
35 changes: 33 additions & 2 deletions baseframe/forms/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,46 @@
from ..signals import exception_catchall


__all__ = ['ValidEmail', 'ValidEmailDomain', 'ValidUrl', 'AllUrlsValid', 'StripWhitespace', 'ValidName',
'NoObfuscatedEmail', 'ValidCoordinates',
__all__ = ['OptionalIf', 'OptionalIfNot', 'ValidEmail', 'ValidEmailDomain', 'ValidUrl', 'AllUrlsValid',
'StripWhitespace', 'ValidName', 'NoObfuscatedEmail', 'ValidCoordinates',
# WTForms validators
'DataRequired', 'InputRequired', 'Optional', 'Length', 'EqualTo', 'URL', 'ValidationError', 'StopValidation']


EMAIL_RE = re.compile(r'\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,63}\b', re.I)


class OptionalIf(object):
"""
Validator that makes this field optional if the value of some other field is true.
"""
def __init__(self, fieldname, message=None):
self.fieldname = fieldname
self.message = message or __("This is required")

def __call__(self, form, field):
print "Validating field", field
if not field.data:
print "Field is empty"
print "Other", bool(getattr(form, self.fieldname).data)
if getattr(form, self.fieldname).data:
raise StopValidation()
else:
raise StopValidation(self.message)


class OptionalIfNot(OptionalIf):
"""
Validator that makes this field optional if the value of some other field is false.
"""
def __call__(self, form, field):
if not field.data:
if not getattr(form, self.fieldname).data:
raise StopValidation()
else:
raise StopValidation(self.message)


class ValidEmail(object):
"""
Validator to confirm an email address is likely to be valid because it is properly
Expand Down

0 comments on commit a14df9a

Please sign in to comment.