Data Validation Best Practices Guide
Use this page when you already have a schema and need to understand validation options, failure paths, and result handling. For the API surface, see validate(), validateAsync(), and Validator.
Quick Start
Basic validation process
DSL syntax quick check
basic type
format type
constraint syntax
special mark
Authentication mode
1. Convenient function validation (recommended)
The simplest way to verify, use the built-in singleton Validator:
2. Validator instance validation (advanced)
Use when custom configuration (such as type conversion, custom keywords) is needed:
Coercion note:
new Validator()already enables schema-dsl's narrow smart coercion for object fields such as string → number/boolean. UsecoerceTypes: truewhen you also need AJV's native coercion behavior; usecoerceTypes: falseorsmartCoerce: falseto disable schema-dsl smart coercion.
Note:
new Validator()will create a new Ajv instance, which has a certain initialization overhead. It is recommended to create and reuse when the application starts to avoid creating it in every request.
3. Precompilation validation (high performance)
Use when validating the same Schema frequently:
4. Batch validation
Use when verifying multiple pieces of data:
Error handling
error object structure
Custom error message
Multilingual error messages
Error formatting
Performance optimization
1. Use precompilation
2. Caching Schema
3. Use allErrors appropriately
4. Monitor performance
Common scenarios
User registration form
API request validation
Profile validation
best practices
1. Use label to improve error message quality
2. Centrally manage Schema
3. Use SchemaUtils to reuse fields
4. Layered validation
Corresponding sample file
Example entry: validation-guide.ts Description: Covers the recommended validation process: defining reusable schema, formatting errors, precompilation reuse, and batch validation.