/protean:custom-validatorfrom protean
Build custom field validators for Protean domain elements, covering format validation (email, phone, URL, SKU, credit card) with RegexValidator, parameterized validators, and chaining multiple validators on a single field.
Ships in protean. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Custom validators are callable classes that validate individual field values. They are the mechanism for enforcing format rules, patterns, and domain-specific constraints on a single field, beyond what built-in field parameters (required, max_length, min_value, choices) provide.
A custom validator is a callable class with __call__ that raises ValidationError on invalid input:
from protean.exceptions import ValidationError
class PhoneValidator:
"""Validates phone number format."""
def __init__(self):
self.error = "Invalid phone number format"
def __call__(self, value):
cleaned = value.replace("-", "").replace(" ", "").replace("(", "").replace(")", "")
if not cleaned.startswith("+"):
raise ValidationError(self.error)
digits = cleaned[1:]
if not digits.isdigit() or not (10 <= len(digits) <= 15):
raise ValidationError(self.error)
Attach to a field with the validators parameter:
@domain.value_object
class Phone:
number: String(required=True, max_length=20, validators=[PhoneValidator()])
__init__ and __call__. The __call__ method receives the field value as its single argument.ValidationError on failure: Import from protean.exceptions. The error message string gets wrapped into {field_name: [message]} automatically. If the validator has an error attribute, that string is the message instead.__call__ has already been cast to the field's native type (e.g., str for String, int for Integer).validators=[V1(), V2()]. They run in list order, and validation stops at the first failing validator. The user sees one error for the field at a time.
The exception is a ValueObject or ValueObjectList field. There, every validator in the list runs, and the field reports one error for each validator that failed.@invariant.post instead (see add-validation).__init__ parameters so they work across multiple fields and domain elements.When a field value is set, Protean validates in this order:
required field without value raises errorchoices enum/list_cast_to_type() converts to native typemax_length, min_length, min_value, max_value, and sanitization. A value that fails one of these never reaches the custom validators.validators=[] list run in order. Validation stops at the first failure. Empty values (None, "", [], (), {}) skip the validators.Protean provides these validators out of the box (used internally by fields):
| Validator | Used by | Purpose |
|---|---|---|
MinLengthValidator(n) | String(min_length=n) | Minimum character count |
MaxLengthValidator(n) | String(max_length=n) | Maximum character count |
MinValueValidator(n) | Integer(min_value=n), Float(min_value=n) | Minimum numeric value |
MaxValueValidator(n) | Integer(max_value=n), Float(max_value=n) | Maximum numeric value |
These are applied automatically. You don't need to add them to validators=[].
For pattern-based validation, use Protean's built-in RegexValidator:
from protean.fields.validators import RegexValidator
@domain.value_object
class ProductCode:
code: String(
required=True,
max_length=10,
validators=[
RegexValidator(
regex=r"^[A-Z]{3}-\d{4}$",
message="Product code must be in format XXX-9999"
)
]
)
RegexValidator supports:
regex: Pattern string or compiled regexmessage: Custom error message (default: "invalid value")inverse_match: If True, fails when pattern DOES matchflags: Regex flags (only when regex is a string)Make validators configurable via constructor parameters:
class AllowedDomainValidator:
"""Validates email belongs to allowed domains."""
def __init__(self, allowed_domains):
self.allowed_domains = allowed_domains
self.error = f"Email must belong to one of: {', '.join(allowed_domains)}"
def __call__(self, value):
domain_part = value.split("@")[-1].lower()
if domain_part not in self.allowed_domains:
raise ValidationError(self.error)
# Reuse with different configurations
corporate_email: String(validators=[AllowedDomainValidator(["company.com", "corp.com"])])
partner_email: String(validators=[AllowedDomainValidator(["partner.org", "vendor.net"])])
Chain validators for layered validation. They run in list order, and validation stops at the first failing validator, so put the most basic check first:
class ReservedWordValidator:
"""Rejects reserved words, ignoring case."""
def __init__(self, reserved_words):
self.reserved_words = [word.lower() for word in reserved_words]
def __call__(self, value):
if value.lower() in self.reserved_words:
raise ValidationError(f"'{value}' is reserved and cannot be used")
@domain.value_object
class Username:
value: String(
required=True,
min_length=3,
max_length=30,
validators=[
RegexValidator(
regex=r"^[a-zA-Z][a-zA-Z0-9_]*$",
message="Username must start with a letter, only letters/digits/underscores"
),
ReservedWordValidator(reserved_words=["admin", "root", "system"]),
]
)
ValueError instead of ValidationError: Always raise ValidationError from protean.exceptions. A ValueError is reported under the field name on a basic field such as String, but under _entity on a ValueObject field, and any other exception type, such as TypeError, propagates unhandled. See anti-patterns.check and resolve what it reportsassets/custom_validator_basic.py (opens in a new tab)assets/custom_validator_composition.py (opens in a new tab)assets/custom_validator_parameterized.py (opens in a new tab)assets/custom_validator_regex.py (opens in a new tab)references/anti-patterns.md (opens in a new tab)references/basic-validators.md (opens in a new tab)references/composing-validators.md (opens in a new tab)references/parameterized-validators.md (opens in a new tab)references/regex-validators.md (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
npx claudepluginhub proteanhq/protean --plugin protean39 skills in this plugin
/add-commandAdd a complete command flow to an existing aggregate. It creates a command class, a FastAPI API endpoint, and a command handler with repository logic. This is the primary workflow for adding write operations to a Protean domain. Use when the user wants to "add a command", "add an action", "add an operation", "expose a write endpoint", "create a command flow", "wire up a POST endpoint", "add a new operation to an aggregate", or describes an action like "I want users to be able to [verb] a [thing]" (e.g., "place an order", "register a user", "cancel a reservation"). This workflow composes the command, command-handler, and api-endpoint element skills./add-domain-service-flowBuild a domain service flow in Protean for business logic that spans two or more aggregates. Domain services are stateless, encapsulate cross-aggregate business rules, and run pre/post invariants for validation. They are used when business logic doesn't naturally belong to a single aggregate. Wire them into command handlers or application services for persistence. Use when the user asks to "add a domain service", "implement cross-aggregate logic", "coordinate multiple aggregates", "add a business operation spanning aggregates", "validate across aggregates", or when they describe scenarios like "placing an order checks inventory and reserves stock", "transferring funds between accounts", "scheduling involves both resource and calendar"./add-eventAdd a complete event flow to an existing aggregate. It creates a domain event, adds or updates an aggregate method that raises the event via self.raise_(), and wires an event handler that processes the event and performs specified side effects (such as syncing state across aggregates, sending notifications, or triggering downstream processes). This is the primary workflow for adding reactive, event-driven behavior to a Protean domain. Use when the user wants to "add an event", "add a domain event", "add a reaction to a state change", "add a side effect", "create an event flow", "wire an event handler", "add event-driven behavior", "react to a state change", "sync aggregates on event", or describes something that happened or should happen (like "when an order is placed, reduce inventory", "after payment is confirmed, send a notification", "when a user registers, create a welcome email", "notify the warehouse when an order ships"). This workflow composes the event, aggregate, and event-handler element skills./add-fieldAdd fields to Protean domain elements (aggregates, entities, value objects). Guides you through selecting the right field type, configuring validations, and placing fields correctly. Use when the user asks to "add a field", "add an attribute", "add a property", "I need to store [data]", "add a new field to [aggregate/entity]", or describes data that needs to be tracked. Covers simple fields, association fields (HasOne, HasMany, ValueObject), field validation, custom validators, and choosing between field types for different use cases./add-read-modelBuild a complete read model in Protean, a projection populated by a projector that reacts to domain events. Covers single-aggregate projections (flattened view of one aggregate), cross-aggregate projections (combining data from multiple aggregates), and choosing between database-backed and cache-backed storage. Use when the user asks to "add a read model", "create a projection with projector", "build a query view", "add a CQRS read side", "create a denormalized view", "build a reporting view", "add a dashboard query model", or when they need to combine data from multiple aggregates into one queryable structure./add-saga-flowBuild a complete saga in Protean using a process manager that coordinates a multi-step flow across several aggregates. The saga reacts to domain events, issues commands to drive each aggregate forward, tracks its own state, and closes on a terminal handler with a compensating path for failures. Use when the user asks to "add a saga", "coordinate a multi-step process", "orchestrate a workflow across aggregates", "manage order fulfillment", "add a process manager flow", "compensate on failure", "roll back a distributed transaction", or when they describe a flow like "reserve stock, take payment, then ship, and undo the reservation if payment fails".Other plugins' skills for the same job