Validate Brazilian Documents
validate-docbr is a Python library designed to validate Brazilian documents such as CPF, CNPJ, CNH, PIS, RENAVAM, and more. It is currently at version 2.0.0 and actively maintained with periodic releases that add new document types and improvements.
Common errors
-
ModuleNotFoundError: No module named 'validate_docbr'
cause The package 'validate-docbr' is not installed or the Python environment is not correctly configured.fixRun `pip install validate-docbr` to install the package. -
AttributeError: module 'validate_docbr' has no attribute 'CPF'
cause You are trying to access a specific document validator (e.g., CPF) directly from the top-level `validate_docbr` module without importing it explicitly.fixEnsure you import the specific validator class: `from validate_docbr import CPF`. -
TypeError: argument of type 'NoneType' is not iterable
cause You are passing `None` as the document value to a validation method which expects a string.fixAlways ensure the document string passed to `validate()` or `is_formatted()` is a non-None string, even if empty. Example: `cpf_validator.validate(document or '')`.
Warnings
- breaking Version 2.0.0 and above require Python 3.10 or newer. Users on older Python versions (e.g., 3.9) will encounter installation errors.
- gotcha The `validate` method returns `True` or `False` directly and does not raise exceptions for invalid inputs. Ensure your code explicitly checks the boolean return value.
- gotcha The library's validation methods generally handle documents with or without standard formatting (e.g., '123.456.789-00' vs '12345678900'). However, methods like `is_formatted` are strict about the exact formatting.
Install
-
pip install validate-docbr
Imports
- CPF
from validate_docbr import CPF
- CNPJ
from validate_docbr import CNPJ
- PIS
from validate_docbr import PIS
- RENAVAM
from validate_docbr import RENAVAM
Quickstart
from validate_docbr import CPF, CNPJ
# Example CPF validation
cpf_validator = CPF()
print(f"Is '123.456.789-00' a valid CPF? {cpf_validator.validate('123.456.789-00')}")
print(f"Is '111.111.111-11' a valid CPF? {cpf_validator.validate('111.111.111-11')}")
# Example CNPJ validation
cnpj_validator = CNPJ()
print(f"Is '11.222.333/0001-81' a valid CNPJ? {cnpj_validator.validate('11.222.333/0001-81')}")
print(f"Is '00.000.000/0000-00' a valid CNPJ? {cnpj_validator.validate('00.000.000/0000-00')}")
# Check if a document is formatted correctly
print(f"Is '123.456.789-00' formatted as a CPF? {cpf_validator.is_formatted('123.456.789-00')}")
print(f"Is '12345678900' formatted as a CPF? {cpf_validator.is_formatted('12345678900')}")