1

I'm trying to restrict registration in my Flask application built with Flask-Security to email addresses from specific domains.

My additional inclination was to override the register_user view from Flask Security, but their docs made it seem like extending the form was the preferred route.

In the following code, I attempt to add a custom validator to email, a field that is already declared within the Flask Security's RegisterForm. The additional validation function is never called. I have tried declaring the variable outside of the class and calling it from within the EmailField, but that doesn't seem to help either.

This is all within app.py.

class RestrictedRegisterForm(RegisterForm):
    email = EmailField(
        'Email', validators=[DataRequired()]
    )

    def validate_email(form, field):
        domain_list = ['foo.com', 'bar.org']
        email_domain = field.data.split("@")[1]
        if email_domain not in domain_list:
            raise ValidationError('Email address must be of an authorized domain')

user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(app, user_datastore, register_form=RestrictedRegisterForm)
user3501855
  • 131
  • 1
  • 1
  • 7
  • Shouldn't your validation method be called `validate_email` as `email` is the name of the field in the form. Also its signature should be `def validate_email(form, field):`. – pjcunningham Oct 21 '16 at 12:12
  • You're right. That was the original incarnation, but I started switching things around once I saw that it didn't work. It's back to that form now. – user3501855 Oct 21 '16 at 13:41
  • I've just ran that code in one of my own projects and it works fine - I did use `InputRequired()` rather than `DataRequired()` though. How are you validating the form ? – pjcunningham Oct 21 '16 at 14:05

0 Answers0