如何验证表单中的电子邮件地址域?

时间:2012-08-13 18:19:54

标签: python django django-forms validation django-validation

给定一个电子邮件地址(例如:goelv@example.com),如何验证域(“example.com”)是否包含在给定的域列表中。如果域(“example.com”)不在指定的列表中,表单应该引发某种错误。

这是我目前在forms.py

中所拥有的
class UserCreationFormExtended(UserCreationForm):
    email = forms.EmailField(required=True)

    class Meta:
        model = User
        fields = ("username", "email", "password1", "password2",)

    def clean_email(self):
        data = self.cleaned_data['email']
        domain = data.split('@')[1]
        domain_list = ["gmail.com", "yahoo.com", "hotmail.com",]
        if domain not in domain_list:
            raise forms.ValidationError["Please enter an Email Address with a valid domain"]
        return data

    def save(self, commit=True):
        user = super(UserCreationFormExtended, self).save(commit=False)
        user.email = self.cleaned_data["email"]
        if commit:
            user.save()
        return user

使用此代码,我收到错误“'type'对象没有属性' getitem '”,它跟踪到我的“raise forms.ValidationError [...]”行代码。

谁能看到我做错了什么?谢谢你的帮助!

2 个答案:

答案 0 :(得分:4)

您需要在()行中使用[]代替raise,如下所示:

raise forms.ValidationError("Please enter a valid Penn Email Address")

答案 1 :(得分:2)

我认为这句话......

raise forms.ValidationError["Please enter an Email Address with a valid domain"]

应该是

raise forms.ValidationError("Please enter an Email Address with a valid domain")