Skip to content

Instantly share code, notes, and snippets.

@mgedmin
Created May 22, 2012 14:12
Show Gist options
  • Save mgedmin/2769326 to your computer and use it in GitHub Desktop.
Save mgedmin/2769326 to your computer and use it in GitHub Desktop.
Custom zope.schema fields for email addresses
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
@mgedmin
Copy link
Author

mgedmin commented May 22, 2012

The regexps aren't very good; they allow a bunch of invalid email addresses past:

email@example'com
email@example
email@0
email@example$com
email@example/com
email@example..com
email@.example.com
email@example-com

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment