Python django.core.validators.validate_email() Examples

The following are 13 code examples of django.core.validators.validate_email(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.core.validators , or try the search function .
Example #1
Source File: message_send.py    From zulip with Apache License 2.0 6 votes vote down vote up
def same_realm_zephyr_user(user_profile: UserProfile, email: str) -> bool:
    #
    # Are the sender and recipient both addresses in the same Zephyr
    # mirroring realm?  We have to handle this specially, inferring
    # the domain from the e-mail address, because the recipient may
    # not existing in Zulip and we may need to make a stub Zephyr
    # mirroring user on the fly.
    try:
        validators.validate_email(email)
    except ValidationError:
        return False

    domain = email_to_domain(email)

    # Assumes allow_subdomains=False for all RealmDomain's corresponding to
    # these realms.
    return user_profile.realm.is_zephyr_mirror_realm and \
        RealmDomain.objects.filter(realm=user_profile.realm, domain=domain).exists() 
Example #2
Source File: email_validation_utils.py    From scantron with Apache License 2.0 5 votes vote down vote up
def check_email_address_validity(email_address):
    """Given a string, determine if it is a valid email address using Django's validate_email() function."""

    try:
        validate_email(email_address)
        valid_email = True

    except ValidationError:
        valid_email = False

    return valid_email 
Example #3
Source File: message_send.py    From zulip with Apache License 2.0 5 votes vote down vote up
def same_realm_irc_user(user_profile: UserProfile, email: str) -> bool:
    # Check whether the target email address is an IRC user in the
    # same realm as user_profile, i.e. if the domain were example.com,
    # the IRC user would need to be username@irc.example.com
    try:
        validators.validate_email(email)
    except ValidationError:
        return False

    domain = email_to_domain(email).replace("irc.", "")

    # Assumes allow_subdomains=False for all RealmDomain's corresponding to
    # these realms.
    return RealmDomain.objects.filter(realm=user_profile.realm, domain=domain).exists() 
Example #4
Source File: message_send.py    From zulip with Apache License 2.0 5 votes vote down vote up
def same_realm_jabber_user(user_profile: UserProfile, email: str) -> bool:
    try:
        validators.validate_email(email)
    except ValidationError:
        return False

    # If your Jabber users have a different email domain than the
    # Zulip users, this is where you would do any translation.
    domain = email_to_domain(email)

    # Assumes allow_subdomains=False for all RealmDomain's corresponding to
    # these realms.
    return RealmDomain.objects.filter(realm=user_profile.realm, domain=domain).exists() 
Example #5
Source File: test_validators.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_all_errors_get_reported(self):
        class UserForm(forms.Form):
            full_name = forms.CharField(
                max_length=50,
                validators=[
                    validators.validate_integer,
                    validators.validate_email,
                ]
            )
            string = forms.CharField(
                max_length=50,
                validators=[
                    validators.RegexValidator(
                        regex='^[a-zA-Z]*$',
                        message="Letters only.",
                    )
                ]
            )
            ignore_case_string = forms.CharField(
                max_length=50,
                validators=[
                    validators.RegexValidator(
                        regex='^[a-z]*$',
                        message="Letters only.",
                        flags=re.IGNORECASE,
                    )
                ]
            )

        form = UserForm({
            'full_name': 'not int nor mail',
            'string': '2 is not correct',
            'ignore_case_string': "IgnORE Case strIng",
        })
        with self.assertRaises(ValidationError) as e:
            form.fields['full_name'].clean('not int nor mail')
        self.assertEqual(2, len(e.exception.messages))

        self.assertFalse(form.is_valid())
        self.assertEqual(form.errors['string'], ["Letters only."])
        self.assertEqual(form.errors['string'], ["Letters only."]) 
Example #6
Source File: test_validators.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_field_validators_can_be_any_iterable(self):
        class UserForm(forms.Form):
            full_name = forms.CharField(
                max_length=50,
                validators=(
                    validators.validate_integer,
                    validators.validate_email,
                )
            )

        form = UserForm({'full_name': 'not int nor mail'})
        self.assertFalse(form.is_valid())
        self.assertEqual(form.errors['full_name'], ['Enter a valid integer.', 'Enter a valid email address.']) 
Example #7
Source File: test_validators.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_all_errors_get_reported(self):
        class UserForm(forms.Form):
            full_name = forms.CharField(
                max_length=50,
                validators=[
                    validators.validate_integer,
                    validators.validate_email,
                ]
            )
            string = forms.CharField(
                max_length=50,
                validators=[
                    validators.RegexValidator(
                        regex='^[a-zA-Z]*$',
                        message="Letters only.",
                    )
                ]
            )
            ignore_case_string = forms.CharField(
                max_length=50,
                validators=[
                    validators.RegexValidator(
                        regex='^[a-z]*$',
                        message="Letters only.",
                        flags=re.IGNORECASE,
                    )
                ]
            )

        form = UserForm({
            'full_name': 'not int nor mail',
            'string': '2 is not correct',
            'ignore_case_string': "IgnORE Case strIng",
        })
        with self.assertRaises(ValidationError) as e:
            form.fields['full_name'].clean('not int nor mail')
        self.assertEqual(2, len(e.exception.messages))

        self.assertFalse(form.is_valid())
        self.assertEqual(form.errors['string'], ["Letters only."])
        self.assertEqual(form.errors['string'], ["Letters only."]) 
Example #8
Source File: test_validators.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_field_validators_can_be_any_iterable(self):
        class UserForm(forms.Form):
            full_name = forms.CharField(
                max_length=50,
                validators=(
                    validators.validate_integer,
                    validators.validate_email,
                )
            )

        form = UserForm({'full_name': 'not int nor mail'})
        self.assertFalse(form.is_valid())
        self.assertEqual(form.errors['full_name'], ['Enter a valid integer.', 'Enter a valid email address.']) 
Example #9
Source File: test_multiplechoicefield.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_field_validates_valid_data(self):
        value = ["test@example.com", "me@example.com"]
        field = ValidatorMultipleChoiceField(validator=validate_email)
        self.assertEqual(value, field.clean(value)) 
Example #10
Source File: test_multiplechoicefield.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_field_uses_validator(self):
        value = ["test@example.com", "invalid-email"]
        field = ValidatorMultipleChoiceField(validator=validate_email)
        error = self.assertRaises(ValidationError, field.clean, value)
        self.assertEqual(["Enter a valid email address."], error.messages) 
Example #11
Source File: validators.py    From modoboa-webmail with MIT License 5 votes vote down vote up
def __call__(self, value):
        value = force_text(value)
        addresses = getaddresses([value])
        [validate_email(email) for name, email in addresses if email] 
Example #12
Source File: registration.py    From zulip with Apache License 2.0 4 votes vote down vote up
def find_account(request: HttpRequest) -> HttpResponse:
    from zerver.context_processors import common_context
    url = reverse('zerver.views.registration.find_account')

    emails: List[str] = []
    if request.method == 'POST':
        form = FindMyTeamForm(request.POST)
        if form.is_valid():
            emails = form.cleaned_data['emails']
            for user in UserProfile.objects.filter(
                    delivery_email__in=emails, is_active=True, is_bot=False,
                    realm__deactivated=False):
                context = common_context(user)
                context.update({
                    'email': user.delivery_email,
                })
                send_email('zerver/emails/find_team', to_user_ids=[user.id], context=context,
                           from_address=FromAddress.SUPPORT)

            # Note: Show all the emails in the result otherwise this
            # feature can be used to ascertain which email addresses
            # are associated with Zulip.
            data = urllib.parse.urlencode({'emails': ','.join(emails)})
            return redirect(add_query_to_redirect_url(url, data))
    else:
        form = FindMyTeamForm()
        result = request.GET.get('emails')
        # The below validation is perhaps unnecessary, in that we
        # shouldn't get able to get here with an invalid email unless
        # the user hand-edits the URLs.
        if result:
            for email in result.split(','):
                try:
                    validators.validate_email(email)
                    emails.append(email)
                except ValidationError:
                    pass

    return render(request,
                  'zerver/find_account.html',
                  context={'form': form, 'current_url': lambda: url,
                           'emails': emails}) 
Example #13
Source File: create_user.py    From zulip with Apache License 2.0 4 votes vote down vote up
def handle(self, *args: Any, **options: Any) -> None:
        if not options["tos"]:
            raise CommandError("""You must confirm that this user has accepted the
Terms of Service by passing --this-user-has-accepted-the-tos.""")
        realm = self.get_realm(options)
        assert realm is not None  # Should be ensured by parser

        try:
            email = options['email']
            full_name = options['full_name']
            try:
                validators.validate_email(email)
            except ValidationError:
                raise CommandError("Invalid email address.")
        except KeyError:
            if 'email' in options or 'full_name' in options:
                raise CommandError("""Either specify an email and full name as two
parameters, or specify no parameters for interactive user creation.""")
            else:
                while True:
                    email = input("Email: ")
                    try:
                        validators.validate_email(email)
                        break
                    except ValidationError:
                        print("Invalid email address.", file=sys.stderr)
                full_name = input("Full name: ")

        try:
            if options['password_file']:
                with open(options['password_file']) as f:
                    pw = f.read()
            elif options['password']:
                pw = options['password']
            else:
                user_initial_password = initial_password(email)
                if user_initial_password is None:
                    raise CommandError("Password is unusable.")
                pw = user_initial_password
            do_create_user(email, pw, realm, full_name, email_to_username(email))
        except IntegrityError:
            raise CommandError("User already exists.")