Check for valid domain name in a string?

Viewed 20676

I am using python and would like a simple regex to check for a domain name's validity. I check at least write domain name.

url = 'https://stackoverflow'
        keyword = 'foo'
        with self.assertRaises(ValueError):
            check_keyword(url, keyword)

I try unit testing on url textfield and there is main.py page where I done the validation main.py-

def check_keyword(url, keyword):

if re.match("^(((([A-Za-z0-9]+){1,63}\.)|(([A-Za-z0-9]+(\-)+[A-Za-z0-9]+){1,63}\.))+){1,255}$" ,url):
   return ValueError("Invalid")

Example

2 Answers

Try this :

# Check if a string is a url
    from django.core.validators import URLValidator
    import requests

    try:
        validate = URLValidator()
        validate(url)
        print("String is a valid URL")
    except:
        print("String is not valid URL")
        raise serializers.ValidationError("String is not valid URL")
    
    # Check if the url exists on the internet
    try:
        response = requests.get(url)
        print("URL is valid and exists on the internet")
    except requests.ConnectionError as exception:
        print("URL does not exist on Internet")
        raise serializers.ValidationError(f'URL {url} does not exist on Internet')

UPDATE : i found a better solution by using python-whois library here valid domain name by whois

Related