Today I Learned

Python validators module

You know what’s never easy – Regular Expressions! I appreciate how powerful they are and I appreciate all those Stack Overflow answers where people share their magical incantations. I recently needed a regex for validating if some user input was a valid domain. Google showed by lots of answers which were fit for purpose but also mentioned in some answers was the Python validators module. I quickly installed with pip:

pip3 install validators

That gave me immediate access to a load of handy validators for:

  • Domains
  • Slugs
  • Email
>>> import validators

>>> validators.domain('bowett.dev')
True
>>> validators.domain('bowett.dev/')
ValidationFailure(func=domain, args={'value': 'bowett.dev/'})

>>> validators.slug('python-validators-module')
True
>>> validators.slug('python.validators.module')
ValidationFailure(func=slug, args={'value': 'python.validators.module'})

>>> validators.email('[email protected]')
True
>>> validators.email('someone@@example.com')
ValidationFailure(func=email, args={'whitelist': None, 'value': 'someone@@example.com'})

There are more things it can validate so it’s worth checking out. It might just save you from getting stuck in regex hell for a little while.