djangoauthentication

email field in Django only for corporate emails


Guys Is it possible in sign up form to limit email input only to corporate emails such as @bp.com @kpmg.com etc so to eliminate non-business emails such as gmail.com yahoo.com etc? So that if user insert xxx@gmail.com the form rejects and ask to insert business emails? I saw such option when i applied for master and they required for recomendation to insert business emails.

What source you would advise to look for or what example of code you can share? If you can sharwe any would be great to have some idea.

My forms.py is

from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm

class UserCreateForm(UserCreationForm):

    class Meta:
        fields = ('username','email','password1','password2')
        model = get_user_model()

    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)
        self.fields['username'].label = 'Display Name'
        self.fields['email'].label = 'Email Address'

Any help would be appreciated.


Solution

  • You can add a validator to your field to check the domain:

    from django.core.validators import RegexValidator
    
    domain_validator = RegexValidator(
        regex='@(bp\.com|kpmg\.com)$',
        message='Domain not valid',
        code='invalid_domain',
    )
    
    class UserCreateForm(UserCreationForm):
        email = forms.EmailField(validators=[domain_validator])
    
        # ...
    

    The regex can probably be improved, but it should work