Skip to content

Commit 1a3f271

Browse files
authored
Merge pull request #97 from binary-butterfly/email-validator-max-length
EmailValidator: Add max_length parameter
2 parents dd4372d + f921579 commit 1a3f271

File tree

3 files changed

+56
-22
lines changed

3 files changed

+56
-22
lines changed

docs/03-basic-validators.md

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -228,24 +228,31 @@ validator_empty_string.validate('') # will return "" (empty string)
228228

229229
The `EmailValidator` validates email addresses as strings and returns them unmodified.
230230

231-
Please note that this validator is a bit opinionated and simplified in that it does **not** allow every email address that technically
232-
is valid according to the RFCs. For example, it does neither allow internationalized email addresses (although this might be changed
233-
in the future), nor oddities like quoted strings as local part or comments, because most mail software does not support those anyway
234-
and/or might break with those adresses.
231+
Please note that this validator is a bit opinionated and simplified in that it does **not** allow every email address
232+
that technically is valid according to the RFCs. For example, it does neither allow internationalized email addresses
233+
(although this might be changed in the future), nor oddities like quoted strings as local part or comments, because most
234+
mail software does not support those anyway and/or might break with those adresses.
235235

236-
Currently this validator has parameter `allow_empty`. To allow empty strings as input, you can set the `allow_empty` parameter to `True` (defaults to `False`).
236+
By default, the validator does not accept empty strings as input. To allow them, set the parameter `allow_empty=True`.
237+
238+
Also, the default maximum string length is set to 256 characters (which would be a really long, but still valid email
239+
address), which can be changed using the `max_length` parameter.
237240

238241
**Example:**
239242

240243
```python
241244
from validataclass.validators import EmailValidator
242245

246+
# Default email validator
243247
validator = EmailValidator()
244248
validator.validate("[email protected]") # will return "[email protected]"
245-
validator.validate("banana") # will return InvalidEmailError(reason='Invalid email address format.')
249+
validator.validate("banana") # will raise InvalidEmailError(reason='Invalid email address format.')
250+
validator.validate("") # will raise StringTooShortError(min_length=1, max_length=256)
246251

247-
validator_empty_string = EmailValidator(allow_empty=True)
248-
validator_empty_string.validate('') # will return "" (empty string)
252+
# Allow empty strings as input
253+
validator = EmailValidator(allow_empty=True)
254+
validator.validate("[email protected]") # will return "[email protected]"
255+
validator.validate("") # will return "" (empty string)
249256
```
250257

251258

src/validataclass/validators/email_validator.py

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -23,12 +23,14 @@ class EmailValidator(StringValidator):
2323
"""
2424
Validator for email addresses.
2525
26-
Please note that this validator is a bit opinionated and simplified in that it does *not* allow every email address that technically
27-
is valid according to the RFCs. For example, it does neither allow internationalized email addresses (although this might be changed
28-
in the future), nor oddities like quoted strings as local part or comments, because most mail software does not support those anyway
29-
and/or might break with those addresses.
26+
Please note that this validator is a bit opinionated and simplified in that it does *not* allow every email address
27+
that technically is valid according to the RFCs. For example, it does neither allow internationalized email
28+
addresses (although this might be changed in the future), nor oddities like quoted strings as local part or comments,
29+
because most mail software does not support those anyway and/or might break with those addresses.
3030
31-
Set the parameter `allow_empty=True` to allow empty strings ('').
31+
Set the parameter `allow_empty=True` to allow empty strings as input.
32+
33+
By default, the maximum string length is set to 256 characters. This can be changed with the `max_length` parameter.
3234
3335
Example:
3436
@@ -53,21 +55,26 @@ class EmailValidator(StringValidator):
5355
# Whether to accept empty strings
5456
allow_empty: bool = False
5557

56-
def __init__(self, *,
57-
allow_empty: bool = False,):
58+
def __init__(
59+
self,
60+
*,
61+
allow_empty: bool = False,
62+
max_length: int = 256,
63+
):
5864
"""
5965
Create a `EmailValidator`.
6066
6167
Parameters:
6268
allow_empty: Boolean, if True, empty strings are accepted as valid email addresses (default: False)
69+
max_length: Integer, maximum length of input string (default: 256)
6370
"""
6471
self.allow_empty = allow_empty
6572

6673
# Allow string with length 0 if `allow_empty=True`
6774
min_length = 0 if allow_empty else 1
6875

6976
# Initialize StringValidator with some length requirements
70-
super().__init__(min_length=min_length, max_length=256)
77+
super().__init__(min_length=min_length, max_length=max_length)
7178

7279
def validate(self, input_data: Any, **kwargs) -> str:
7380
"""

tests/validators/email_validator_test.py

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ def test_invalid_wrong_type():
3434

3535
@staticmethod
3636
def test_invalid_empty_string():
37-
""" Check that EmailValidator raises exceptions for empty strings. """
37+
""" Check that EmailValidator raises exceptions for empty strings by default. """
3838
validator = EmailValidator()
3939
with pytest.raises(StringInvalidLengthError) as exception_info:
4040
validator.validate('')
@@ -56,26 +56,46 @@ def test_invalid_empty_string():
5656
]
5757
)
5858
def test_allow_empty_valid(input_string):
59-
""" Check that EmailValidator returns empty string if boolean parameter allow_empty=True. """
59+
""" Test that EmailValidator returns empty string if boolean parameter allow_empty=True. """
6060
validator = EmailValidator(allow_empty=True)
6161
assert validator.validate(input_string) == input_string
6262

63+
# Test maximum string length
64+
6365
@staticmethod
64-
def test_invalid_string_too_long():
65-
""" Check that EmailValidator raises exceptions for strings that are too long. """
66+
@pytest.mark.parametrize('allow_empty', [True, False])
67+
def test_invalid_string_too_long(allow_empty):
68+
""" Test that EmailValidator raises exceptions for strings that are too long. """
6669
# Construct an email address that is technically valid but too long
6770
input_string = ('a' * 64) + '@' + ('very-very-very-very-very-very-very-long-domain.' * 4)
6871
input_string += 'b' * (257 - len(input_string))
6972

70-
validator = EmailValidator()
73+
validator = EmailValidator(allow_empty=allow_empty)
7174
with pytest.raises(StringInvalidLengthError) as exception_info:
7275
validator.validate(input_string)
7376
assert exception_info.value.to_dict() == {
7477
'code': 'string_too_long',
75-
'min_length': 1,
78+
'min_length': 0 if allow_empty else 1,
7679
'max_length': 256,
7780
}
7881

82+
@staticmethod
83+
def test_max_length_parameter():
84+
""" Test EmailValidator with a custom value for max_length. """
85+
validator = EmailValidator(max_length=16)
86+
87+
# Valid input (16 characters)
88+
assert validator.validate('[email protected]')
89+
90+
# Invalid input (17 characters)
91+
with pytest.raises(StringInvalidLengthError) as exception_info:
92+
validator.validate('[email protected]')
93+
assert exception_info.value.to_dict() == {
94+
'code': 'string_too_long',
95+
'min_length': 1,
96+
'max_length': 16,
97+
}
98+
7999
# Tests for regex validation of email address format
80100

81101
@staticmethod

0 commit comments

Comments
 (0)