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

feat: add is_email_valid #213

Merged
merged 4 commits into from
Oct 4, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Added

- Utilitário `is_valid_email` [#213](https://github.com/brazilian-utils/brutils-python/pull/213)
- Utilitário `is_valid_phone` [#147](https://github.com/brazilian-utils/brutils-python/pull/147)
- Utilitário `is_valid_mobile_phone` [#146](https://github.com/brazilian-utils/brutils-python/pull/146)
- Utilitário `is_valid_landline_phone` [#143](https://github.com/brazilian-utils/brutils-python/pull/143)
Expand Down
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@ False
- [is_valid_mobile_phone](#is_valid_mobile_phone)
- [is_valid_landline_phone](#is_valid_landline_phone)
- [remove_symbols_phone](#remove_symbols_phone)
- [Email](#email)
- [is_valid_email](#is_valid_email)

## CPF

Expand Down Expand Up @@ -241,6 +243,25 @@ Remove símbolos do número de telefone. ***Exemplo: (21)2569-6969 ficaria '2125
'2125696969'
```

## Email

### is_valid_email

Verificar se uma string corresponde a um e-mail válido. As regras para validar um endereço de e-mail geralmente seguem as especificações definidas pelo RFC 5322 (atualizado pelo RFC 5322bis), que é o padrão amplamente aceito para formatos de endereços de e-mail.

```python
from brutils import is_valid_email

>>> is_valid_email("[email protected]")
True
>>> is_valid_email("[email protected]")
False
>>> is_valid_email("joao.ninguem@gmail.")
False
>>> is_valid_email("joao [email protected]")
False
```

# Novos Utilitários e Reportar Bugs

Caso queira sugerir novas funcionalidades ou reportar bugs, basta criar
Expand Down
20 changes: 20 additions & 0 deletions README_EN.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@ False
- [is_valid_mobile_phone](#is_valid_mobile_phone)
- [is_valid_landline_phone](#is_valid_landline_phone)
- [remove_symbols_phone](#remove_symbols_phone)
- [Email](#email)
- [is_valid_email](#is_valid_email)


## CPF
Expand Down Expand Up @@ -237,6 +239,24 @@ Remove symbols from phone number. ***Example: +55 (21) 2569-6969 will return '55
>>> remove_symbols_phone('+55 (21) 2569-6969')
'552125696969'
```
## Email

### is_valid_email

Check if a string corresponds to a valid email. The rules for validating an email address generally follow the specifications defined by RFC 5322 (updated by RFC 5322bis), which is the widely accepted standard for email address formats.

```python
from brutils import is_valid_email

>>> is_valid_email("[email protected]")
True
>>> is_valid_email("[email protected]")
False
>>> is_valid_email("joao.ninguem@gmail.")
False
>>> is_valid_email("joao [email protected]")
False
```

# Feature Request and Bug Report

Expand Down
2 changes: 2 additions & 0 deletions brutils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,5 @@
is_valid_mobile as is_valid_mobile_phone,
is_valid as is_valid_phone,
)

from brutils.email import is_valid_email as is_valid_email
17 changes: 17 additions & 0 deletions brutils/email.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import re


def is_valid_email(email): # type: (str) -> bool
"""
Check if a string corresponds to a valid email address.

Args:
email (str): The input string to be checked.

Returns:
bool: True if email is a valid email address, False otherwise.
"""
pattern = re.compile(
r"^(?![.])[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
)
return isinstance(email, str) and re.match(pattern, email) is not None
53 changes: 53 additions & 0 deletions tests/test_email.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import unittest
from brutils import is_valid_email


class TestEmailValidation(unittest.TestCase):
def test_valid_email(self):
# Valid email addresses
valid_emails = [
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
]
for email in valid_emails:
try:
self.assertTrue(is_valid_email(email))
except:
print(f"AssertionError for email: {email}")
raise AssertionError

def test_invalid_email(self):
# Invalid email addresses
invalid_emails = [
"[email protected]",
"joao [email protected]",
"not_an_email",
"@missing_username.com",
"user@incomplete.",
"[email protected]",
"user@inva!id.com",
"user@missing-tld.",
]
for email in invalid_emails:
try:
self.assertFalse(is_valid_email(email))
except:
print(f"AssertionError for email: {email}")
raise AssertionError

def test_non_string_input(self):
# Non-string input should return False
non_strings = [None, 123, True, ["[email protected]"]]
for value in non_strings:
self.assertFalse(is_valid_email(value))

def test_empty_string(self):
# Empty string should return False
self.assertFalse(is_valid_email(""))


if __name__ == "__main__":
unittest.main()