Home > flask, python > [flask] validate a URL

[flask] validate a URL

In a Flask application I wanted to verify if a user-given URL is valid.

I found a simple validator package for that called validators (see it on GitHub).

Sample usage:

$ pip install validators
$ python
>>> import validators
>>> url = "http://index.hu"
>>> validators.url(url)
>>> url = "http://index.h/"
>>> validators.url(url)
ValidationFailure(func=url, args={'value': 'http://index.h/', 'require_tld': True})

The ValidationFailure class implements the __bool__ method, so you can easily check if validation failed:

if not validators.url(url):
    flash("Error: you must provide a valid URL!")
Categories: flask, python Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: