有人能解释一下如何在 Django 中验证电子邮件地址吗? 因此,例如,我想检查电子邮件是否是以 .edu 结尾的有效大学电子邮件地址。 我怎样才能做到这一点?
from django import forms
from .models import SignUp
class SignUpForm(forms.ModelForm):
class Meta:
model = SignUp
fields = ['full_name','email']
def clean_email(self):
email = self.cleaned_data.get('email')
return email
假设您的
SignUp.email
字段是一个 EmailField
,Django 将负责验证它是一个有效的电子邮件地址。您需要做的就是检查它是否以 .edu
结尾,如果不是,则提出 ValidationError
。
class SignUpForm(forms.ModelForm):
class Meta:
model = SignUp
fields = ['full_name','email']
def clean_email(self):
email = self.cleaned_data.get('email')
if not email.endswith('.edu'):
raise forms.ValidationError("Only .edu email addresses allowed")
return email
如果创建一个验证器并将其添加到您的模型字段可能会更好。这样,Django 将在您使用
SignUpForm
时以及在 Django 管理员等其他地方进行模型验证时运行您的验证器。
from django.core.exceptions import ValidationError
def validate_edu_email_address(value):
if email.endswith('.edu'):
raise forms.ValidationError("Only .edu email addresses allowed")
class SignUp(models.Model):
email = models.EmailField(validators=[validate_edu_email_address])
...
只需为您的需要创建一个正则表达式,或者更好地使用一些标准表达式。
import re
EMAIL_REGEX = r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"
# EMAIL_REGEX = r'\w+@\.edu' # If you only want to allow edu.
class SignUpForm(forms.ModelForm):
...
def clean_email(self):
email = self.cleaned_data.get('email')
if email and not re.match(EMAIL_REGEX, email):
raise forms.ValidationError('Invalid email format')
return email
EmailField
,这会自动确保您使用相同的方式(除非您真的需要将电子邮件地址限制为您的自定义格式)。
**如果你想在 Django 表单中修改电子邮件 **
email_user_part_regex = re.compile(
r"^(?=.{4,30}$)[\w\u0080-\uffff]+(?:[\.\-+][\w\u0080-\uffff]+)*$",
re.IGNORECASE | re.UNICODE,
)
class ForgetPasswordEmailForm(forms.Form):
email = forms.EmailField(label='email', max_length=200)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
validate_email.user_regex = email_user_part_regex