Archive

Posts Tagged ‘validator’

validate an IP address (either IPv4 or IPv6)

January 9, 2017 2 comments

Problem
You want to validate an IP address. However, it can be either IPv4 or IPv6.

Solution
Python 3 has a built-in module for this: ipaddress. Example:

>>> ipaddress.ip_address('192.168.0.1')
IPv4Address('192.168.0.1')
>>> ipaddress.ip_address('2001:db8::')
IPv6Address('2001:db8::')

If the IP is invalid, you get a ValueError exception.

Advertisements
Categories: python Tags: , , ,

[flask] validate a URL

August 23, 2015 Leave a comment

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

Solution
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)
True
>>> 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: ,