Custom Schemas
Extend validators with refinements, transforms, and preprocessing
Custom Schemas
While valrs provides built-in primitive validators, you'll often need to add custom constraints, transform values, or preprocess input. valrs provides a Zod-compatible fluent API for these operations.
Refinements
Use .refine() to add custom validation logic that doesn't change the type:
Multiple Refinements
Chain refinements for multiple validation rules:
SuperRefine
Use .superRefine() when you need to add multiple validation issues at once:
Adding Path Information
Include paths for nested validation errors:
Transform
Use .transform() to change the output type after validation:
Validate After Transform with Pipe
Use .pipe() to validate the transformed value:
Common Transform Patterns
Preprocess
Use v.preprocess() to transform input before validation. This is useful for coercing types:
Preprocess vs Transform
- preprocess: Runs before validation, input type is
unknown - transform: Runs after validation, input type is validated
Async Validation
All refinement and transform methods support async operations:
Safe Async Parsing
Complex Object Validation
Combine refinements with object schemas for cross-field validation:
Best Practices
1. Use the Right Tool
2. Validate After Transform
3. Keep Validation Pure
Refinement functions should be pure (no side effects):
4. Use Descriptive Error Messages
5. Include Paths for Nested Errors
Next Steps
- JSON Schema - Export your schemas to JSON Schema
- Standard Schema - How valrs implements the spec
- API Reference - Complete API documentation