virusdefender
2015-10-23 08:35:53 +08:00
django 匹配邮箱的正则,你可以参考,这个都标准了吧
def validate(self, value):
value = super(EmailField, self).validate(value)
user_regex = re.compile(
r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*$"
r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-\011\013\014\016-\177])*"$)',
re.IGNORECASE)
domain_regex = re.compile(
r'(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}|[A-Z0-9-]{2,}(?<!-))$'
# literal form, ipv4 address (SMTP 4.1.3)
r'|^\[(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}\]$',
re.IGNORECASE)
domain_whitelist = ['localhost']
if '@' not in value:
raise ValidationError("Email format is not correct")
user_part, domain_part = value.rsplit('@', 1)
if not user_regex.match(user_part):
raise ValidationError("Email format is not correct")
if (domain_part not in domain_whitelist and
not domain_regex.match(domain_part)):
# Try for possible IDN domain-part
try:
domain_part = domain_part.encode('idna').decode('ascii')
if not domain_regex.match(domain_part):
raise ValidationError("Email format is not correct")
else:
return
except UnicodeError:
pass
raise ValidationError("Invalid Email format")
return value