How to validate domain of email address in form?

Viewed 3266

Given an email address (ex: goelv@example.com), how do I validate that the domain ("example.com") is included in a given list of domains. If the domain ("example.com") is not in the specified list, the form should raise some sort of error.

This is what I have so far in 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

With this code, I'm getting the error "'type' object has no attribute 'getitem'" which traces to the line "raise forms.ValidationError[...]" in my code.

Can anyone see what I'm doing wrong? Thanks for the help!

2 Answers
Related