9

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

Vipul Gangwar
  • 129
  • 1
  • 1
  • 9

1 Answers1

13

The source of the validators module shows, that this is maybe a little more complex task.

You could use that module:

>>> import validators
>>> validators.domain('example.com')
True

>>> validators.domain('example.com/')
ValidationFailure(func=domain, ...)

Or you can use the RFCs for Domain names to construct your own checker.

Christian König
  • 3,100
  • 14
  • 26
  • I am using that same module and the regular expression that it uses looks weird. Also, it gives this domain as valid: "a.aa*com" and I think it shouldn't be, specially because it has got an asterisk as a part of it. – user3289695 Sep 28 '17 at 12:52
  • validators.domain("example.com") cannot check for subdomains. So, It wiil return True for validators.domain("abc.example.com") also. – Akash Wankhede May 19 '20 at 06:28
  • The validators package marks domains with [underscores](https://github.com/kvesteri/validators/issues/102) or [trailing dots](https://github.com/kvesteri/validators/issues/141) as invalid. – Nemo Jun 23 '20 at 22:50