Is Valid Email Kata¶
Write a Python function that returns True or False to indicate whether the passed value is a valid email address or not.
Tests
tests/test_is_email.py¶
1 import unittest
2 import parameterized
3
4 from ..validators import is_email
5
6 class TestIsEmailFunction(unittest.TestCase):
7 @parameterized.parameterized.expand([
8 ('value is simple email address', 'example@example.com'),
9 ('domian is a subdomain', 'example@subdomain.domain.com'),
10 ('domain contains dashes', 'example@example-domain.com'),
11 ('username contains digits', 'example123@example.com'),
12 ])
13 def test_should_return_true_when(self, name, value):
14 self.assertTrue(is_email(value))
15
16 @parameterized.parameterized.expand([
17 ('domain is empty', 'example@'),
18 ('host is empty', 'example@.com'),
19 ('at character is missing', 'example.com'),
20 ('domain ends with period', 'example@com.'),
21 ('domain starts with period', 'example@.domain.com'),
22 ('username is empty', '@domain.com'),
23 ])
24 def test_should_return_false_when(self, name, value):
25 self.assertFalse(is_email(value))
Solution 1
validator.py¶
1import re
2
3def is_email(value):
4 pattern = r'^[a-zA-Z0-9._%+-]+@([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}$'
5
6 regex = re.compile(pattern)
7 match = regex.search(value)
8
9 return bool(match)