I'm trying to write some code that will take in a "supposed" domain name and will validate it according to RFC 1035. For instance, it would need to satisfy these rules:
[a-z0-9\-]
only (will lower case the domain on input)google--com.com
)I have searched for various Python modules (eg: tldextract) but to no avail.
How can I validate that a domain name conforms to RFC 1035?
KISS:
import string
VALID_CHARS = string.lowercase + string.digits + '-.'
def is_valid_domain(domain):
if not all(char in VALID_CHARS for char in domain.lower()):
return False
if len(domain) > 253:
return False
if '--' in domain:
return False
if '..' in domain:
return False
return True
There are times for cleverness, but this doesn't seem to be one of them.
I think it's pretty simple to solve this for yourself, as long as you're only concerned with RFC 1035 domains. Later specifications allow more kinds of domain names, so this will not be enough for the real world!
Here's a solution that uses a regex to match domain names that follow the "preferred name syntax" described on pages 6 and 7 of the RFC. It handles the everything but the top level limit on the number of characters with a single pattern:
import re
def validate_domain_name(name):
if len(name) > 255: return False
pattern = r"""(?X) # use verbose mode for this pattern
^ # match start of the input
(?: # non-capturing group for the whole name
[a-zA-Z] # first character of first label
(?: # non-capturing group for the rest of the first label
[a-zA-Z0-9\-]{,61} # match middle characters of label
[a-zA-Z0-9] # match last character of a label
)? # characters after the first are optional
(?: # non-capturing group for later labels
\. # match a dot
[a-zA-Z](?:[a-zA-Z0-9\-]{,61}[a-zA-Z0-9])? # match a label as above
)* # there can be zero or more labels after the first
)? # the whole name is optional ("" is valid)
$ # match the end of the input"""
return re.match(pattern, name) is not None # test and return a Boolean
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With