Validators
Validators is a lightweight Python library designed for human-friendly data validation without the need for complex schemas or forms. It provides a wide array of simple functions to validate common data types such as email addresses, URLs, IP addresses, and more. On success, validator functions return `True`; on failure, they return a `ValidationFailure` object. The library is actively maintained, with frequent updates to add new validators and improve existing ones.
Warnings
- breaking Version 0.35.0 dropped support for Python 3.8. Users on Python 3.8 or older must upgrade their Python version or use an older `validators` release.
- breaking The `btc_address` validator was moved to the `crypto_addresses` submodule. Direct imports or calls to `validators.btc_address` will fail.
- gotcha Validator functions return `True` on success or a `ValidationFailure` object on failure. While `ValidationFailure` objects correctly evaluate to `False` in a boolean context, they are not `False` themselves. Access specific error details via attributes like `failure_object.message`, `failure_object.value`, etc.
- gotcha Be mindful of similarly named but distinct libraries like `validator` (for request validation with schema rules) and `validator-collection` (another collection of validation functions with a different API). Ensure you are installing and importing the correct `validators` library.
Install
-
pip install validators
Imports
- validators
import validators
Quickstart
import validators
email_to_check = "test@example.com"
is_valid_email = validators.email(email_to_check)
if is_valid_email:
print(f"'{email_to_check}' is a valid email address.")
else:
# ValidationFailure objects evaluate to False in a boolean context
print(f"'{email_to_check}' is not a valid email address. Reason: {is_valid_email.message}")
url_to_check = "http://invalid.domain"
is_valid_url = validators.url(url_to_check)
if is_valid_url:
print(f"'{url_to_check}' is a valid URL.")
else:
print(f"'{url_to_check}' is an invalid URL. Reason: {is_valid_url.message}")