Created
May 22, 2012 14:12
-
-
Save mgedmin/2769326 to your computer and use it in GitHub Desktop.
Custom zope.schema fields for email addresses
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CustomValidationErrorMixin(object): | |
"""Schema field with a custom validation error message. | |
Mix this class with your schema fields and specify | |
which exception they should raise by overriding the | |
_validation_exception attribute. | |
""" | |
_validation_exception = ConstraintNotSatisfied | |
def _validate(self, value): | |
try: | |
super(CustomValidationErrorMixin, self)._validate(value) | |
except ConstraintNotSatisfied: | |
raise self._validation_exception, value | |
class InvalidEmail(ValidationError): | |
"""This does not look like a valid email address""" | |
ASCII_EXCEPT_SPACE_AND_AT = r'[\x21-\x3F\x41-\x7E]' | |
class EmailAddressOnly(CustomValidationErrorMixin, TextLine): | |
"""A text field for email addresses. | |
Accepts only emails (no real name part, no comments, no angle brackets). | |
""" | |
# This is slightly more and slightly less than RFC-2822 allows | |
constraint = re.compile(r'^%s+@[^. @]%s*[^\'@ ]$' % ( | |
ASCII_EXCEPT_SPACE_AND_AT, | |
ASCII_EXCEPT_SPACE_AND_AT)).match | |
_validation_exception = InvalidEmail | |
class EmailWithFullName(CustomValidationErrorMixin, TextLine): | |
"""A text field for RFC-2822 email addresses. | |
Accepts "Name <addr@ess>" as well as "addr@ess". | |
""" | |
# allow all printable US-ASCII characters except SPACE | |
# this is slightly more and slightly less than RFC-2822 allows | |
constraint = re.compile(r'^%s+@%s+$' | |
r'|^.* +<%s+@%s+>' | |
% (ASCII_EXCEPT_SPACE_AND_AT, | |
ASCII_EXCEPT_SPACE_AND_AT, | |
ASCII_EXCEPT_SPACE_AND_AT, | |
ASCII_EXCEPT_SPACE_AND_AT)).match | |
_validation_exception = InvalidEmail |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The regexps aren't very good; they allow a bunch of invalid email addresses past: