Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/validators/domain.py: 100%

10 statements  

« prev     ^ index     » next       coverage.py v7.2.7, created at 2023-06-07 06:08 +0000

1"""Domain.""" 

2# -*- coding: utf-8 -*- 

3 

4# standard 

5import re 

6 

7# local 

8from .utils import validator 

9 

10 

11@validator 

12def domain(value: str, /, *, rfc_1034: bool = False, rfc_2782: bool = False): 

13 """Return whether or not given value is a valid domain. 

14 

15 Examples: 

16 >>> domain('example.com') 

17 # Output: True 

18 >>> domain('example.com/') 

19 # Output: ValidationFailure(func=domain, ...) 

20 >>> # Supports IDN domains as well:: 

21 >>> domain('xn----gtbspbbmkef.xn--p1ai') 

22 # Output: True 

23 

24 Args: 

25 value: 

26 Domain string to validate. 

27 rfc_1034: 

28 Allow trailing dot in domain name. 

29 Ref: [RFC 1034](https://www.rfc-editor.org/rfc/rfc1034). 

30 rfc_2782: 

31 Domain name is of type service record. 

32 Ref: [RFC 2782](https://www.rfc-editor.org/rfc/rfc2782). 

33 

34 

35 Returns: 

36 (Literal[True]): 

37 If `value` is a valid domain name. 

38 (ValidationFailure): 

39 If `value` is an invalid domain name. 

40 

41 Note: 

42 - *In version 0.10.0*: 

43 - Added support for internationalized domain name (IDN) validation. 

44 

45 > *New in version 0.9.0*. 

46 """ 

47 if not value: 

48 return False 

49 try: 

50 return not re.search(r"\s", value) and re.match( 

51 # First character of the domain 

52 rf"^(?:[a-zA-Z0-9{'_'if rfc_2782 else ''}]" 

53 # Sub domain + hostname 

54 + r"(?:[a-zA-Z0-9-_]{0,61}[A-Za-z0-9])?\.)" 

55 # First 61 characters of the gTLD 

56 + r"+[A-Za-z0-9][A-Za-z0-9-_]{0,61}" 

57 # Last character of the gTLD 

58 + rf"[A-Za-z]{r'.$' if rfc_1034 else r'$'}", 

59 value.encode("idna").decode("utf-8"), 

60 re.IGNORECASE, 

61 ) 

62 except UnicodeError: 

63 return False