Dean
Dean

Reputation: 8988

Check for specific email address in form

I'm writing an application in django that needs to only allow a form to be submitted if the email address is that of a specified domain. For example is:

[email protected]

And doesn't allow:

[email protected] 

or any other domain. So how can I do this in django to see if the email address belongs to a specified domain? Should I just split the string from the email address field and do a check on the domain or is there a better approach?

Upvotes: 1

Views: 348

Answers (1)

Paulo Scardine
Paulo Scardine

Reputation: 77281

For example:

class MyForm(forms.ModelForm):
    ...
    def clean_email(self):
        email = self.cleaned_data.get('email', '')
        if email.endswith('@gmail.com'):
            return email
        raise forms.ValidationError('invalid domain')
    ...

Upvotes: 6

Related Questions