Skip to content

Commit

Permalink
Improve the regex used for NameEmail validation (#6125)
Browse files Browse the repository at this point in the history
  • Loading branch information
dmontagu committed Jun 14, 2023
1 parent 8ff1b99 commit a08dda7
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
13 changes: 11 additions & 2 deletions pydantic/networks.py
Expand Up @@ -376,7 +376,15 @@ def _validate(cls, __input_value: NetworkType, _: core_schema.ValidationInfo) ->
return cls(__input_value) # type: ignore[return-value]


pretty_email_regex = re.compile(r' *([\w ]*?) *<(.+?)> *')
def _build_pretty_email_regex() -> re.Pattern:
name_chars = r'[\w!#$%&\'*+\-/=?^_`{|}~]'
unquoted_name_group = fr'((?:{name_chars}+\s+)*{name_chars}+)'
quoted_name_group = r'"((?:[^"]|\")+)"'
email_group = r'<\s*(.+)\s*>'
return re.compile(rf'\s*(?:{unquoted_name_group}|{quoted_name_group})?\s*{email_group}\s*')


pretty_email_regex = _build_pretty_email_regex()


def validate_email(value: str) -> tuple[str, str]:
Expand All @@ -395,7 +403,8 @@ def validate_email(value: str) -> tuple[str, str]:
m = pretty_email_regex.fullmatch(value)
name: str | None = None
if m:
name, value = m.groups()
unquoted_name, quoted_name, value = m.groups()
name = unquoted_name or quoted_name

email = value.strip()

Expand Down
3 changes: 3 additions & 0 deletions tests/test_networks.py
Expand Up @@ -751,6 +751,8 @@ class Model(BaseModel):
('аррӏе@example.com', 'аррӏе', 'аррӏе@example.com'),
('xn--80ak6aa92e@example.com', 'xn--80ak6aa92e', 'xn--80ak6aa92e@example.com'),
('葉士豪@臺網中心.tw', '葉士豪', '葉士豪@臺網中心.tw'),
('"first.last" <first.last@example.com>', 'first.last', 'first.last@example.com'),
("Shaquille O'Neal <shaq@example.com>", "Shaquille O'Neal", 'shaq@example.com'),
],
)
def test_address_valid(value, name, email):
Expand Down Expand Up @@ -785,6 +787,7 @@ def test_address_valid(value, name, email):
('foobar <foobar@example.com>>', None),
('foobar <<foobar<@example.com>', None),
('foobar <>', None),
('first.last <first.last@example.com>', None),
],
)
def test_address_invalid(value, reason):
Expand Down

0 comments on commit a08dda7

Please sign in to comment.