Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate domain of email address in form?

Given an email address (ex: [email protected]), 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!

like image 686
goelv Avatar asked Aug 13 '12 18:08

goelv


People also ask

How do you validate a domain email?

The process You select an email from the list. The Certificate Authority sends a verification email (also called DCV email) to the recipient with a unique link to approve the certificate and validate your domain ownership. You click on the link to validate and approve the certificate.

Which Validator is used to validate the email address?

There are many free tools that also validate email addresses; ValidateEmailAddress, EmailValidator and Pabbly Email Verification are few of such examples.


2 Answers

You need to use () instead of [] in your raise line, like this:

raise forms.ValidationError("Please enter a valid Penn Email Address")
like image 108
girasquid Avatar answered Sep 20 '22 13:09

girasquid


I think the line...

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

Should be

raise forms.ValidationError("Please enter an Email Address with a valid domain")
like image 36
George Avatar answered Sep 22 '22 13:09

George