Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use django regex to validate email addresses #256

Merged
merged 1 commit into from
Apr 27, 2016

Conversation

omarkhan
Copy link
Contributor

@omarkhan omarkhan commented Apr 27, 2016

Background

Django's email validation is much stricter than Angular's. In particular, Angular allows any domain, including those without a tld:

foo@bar

This can cause the form to validate client-side but fail to validate on the server.

Proposal

Use the same regex as Django to validate email addresses.

Implementation

Django uses a combination of 3 regexes and some custom code to validate email addresses. Rather than try to replicate that logic exactly, I have added a get_email_regex method to the EmailFieldMixin class that concatenates the user and domain regexes (including whitelisted domains) into a single javascript-compatible regex. This regex is then added to the input as the email-pattern attribute. If the validate-email directive is included on the input element, this pattern will be used to validate email addresses instead of the Angular default email validation. For example:

class MyForm(NgFormValidationMixin, NgForm):
    email = forms.EmailField(widget=forms.widgets.EmailInput(attrs={
        'validate-email': True
    }))

Caveats

  • Internationalized domain names are not supported
  • IP addresses not supported
  • The Django regex checks that email addresses do not end with a hyphen - character using a negative lookbehind. Javascript regexes do not support lookbehinds, so this is stripped.

@jrief
Copy link
Owner

jrief commented Apr 27, 2016

Thanks for this PR, this annoyed me a little bit myself.
Just for curiosity, why do you extract the Regex from the email field instead of hard coding it?

@omarkhan
Copy link
Contributor Author

Just to keep it DRY.

@jrief jrief merged commit b7b7902 into jrief:master Apr 27, 2016
@jrief
Copy link
Owner

jrief commented May 2, 2016

your PR has been published in
https://pypi.python.org/pypi/django-angular/0.8.2

@omarkhan
Copy link
Contributor Author

omarkhan commented May 2, 2016 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants