Protoc-gen-validate (Python)

1.3.3 · active · verified Thu Apr 16

Protoc-gen-validate provides robust data validation for Protocol Buffers. This Python library serves as the runtime component for validation code generated by the `protoc-gen-validate` plugin. It allows Python applications to enforce complex validation rules defined directly within `.proto` files, ensuring data integrity at the message level. The current version is 1.3.3, with releases often occurring to fix packaging or Python version compatibility issues.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use the generated validation functions and catch `ValidationError` exceptions for Protobuf messages in Python. It assumes that you have already defined your `.proto` messages with validation rules and used the `protoc` compiler with the `protoc-gen-validate` plugin to generate the Python `_pb2.py` and `_pb2_validate.py` files.

# This quickstart assumes you have already defined a .proto file with validation rules
# (e.g., example.proto) and generated the Python protobuf and validation stubs:
#
# example.proto content:
# syntax = "proto3";
# package example;
# import validate/validate.proto;
#
# message Person {
#   int32 id = 1 [(validate.rules).int32.gt = 0];
#   string email = 2 [(validate.rules).string.email = true];
#   string name = 3 [(validate.rules).string.min_len = 1];
# }
#
# Generation command (requires 'protoc' and 'protoc-gen-validate' binaries):
# protoc --plugin=protoc-gen-validate --validate_out=. --python_out=. example.proto

from example_pb2 import Person
from example_pb2_validate import validate as validate_person
from protoc_gen_validate.validator import ValidationError

# --- Example 1: Valid Person ---
print("\n--- Valid Person Example ---")
try:
    p_valid = Person(id=1, email="alice@example.com", name="Alice Smith")
    validate_person(p_valid)
    print(f"Validation successful for: {p_valid.name}")
except ValidationError as e:
    print(f"Validation unexpectedly failed for valid person: {e}")

# --- Example 2: Invalid Person (id <= 0) ---
print("\n--- Invalid Person (ID) Example ---")
try:
    p_invalid_id = Person(id=0, email="bob@example.com", name="Bob Johnson")
    validate_person(p_invalid_id)
    print(f"Validation unexpectedly passed for invalid ID: {p_invalid_id.name}")
except ValidationError as e:
    print(f"Validation failed for invalid ID (as expected): {e}")

# --- Example 3: Invalid Person (empty name) ---
print("\n--- Invalid Person (Name) Example ---")
try:
    p_invalid_name = Person(id=2, email="charlie@example.com", name="")
    validate_person(p_invalid_name)
    print(f"Validation unexpectedly passed for empty name: {p_invalid_name.email}")
except ValidationError as e:
    print(f"Validation failed for empty name (as expected): {e}")

view raw JSON →