Cross-type union validation - types: syntax
Overview
The types: syntax allows you to define cross-type joint validation, supporting field matching of multiple different data types.
characteristic
✅ Concise syntax - 'types:string|number' One line to do it
✅ With restraints - 'types:string:3-10|number:0-100'
✅ Custom extensions - Supports reusable type registration
✅ Multi-language - full i18n support
quick start
Basic usage
With constraints
Grammar instructions
basic format
types:- fixed prefixtype1|type2- list of types, separated by|!- optional required tag
constrained format
Supported types
built-in types
All built-in types are available in types::
- Basic types:
string,number,integer,boolean,null,any - Format type:
email,url,uuid,date,datetime,time - Special types:
phone,idCard,objectId,hexColor, etc.
Plug-in custom type
Custom types registered via plugins can also be used:
Practical application scenarios
Scenario 1: User registration (email or mobile phone number)
Scenario 2: Flexible price input
Scenario 3: Order query (order number or SKU)
Plug-in Development Guide
Register a custom type
DslBuilder API
DslBuilder.registerType(name, schema)
Register a custom type. Parameters:
name(string) - type nameschema(Object|Function) - JSON Schema object or generated function
DslBuilder.hasType(type)
Check if the type is registered.
DslBuilder.getCustomTypes()
Get all registered custom types.
DslBuilder.unregisterType(name)
Remove one custom type registered through DslBuilder.registerType() / TypeRegistry.
DslBuilder.clearCustomTypes()
Clear all custom types (mainly for testing).
Multi-language support
Chinese
English
Supported languages: zh-CN, en-US, es-ES, fr-FR, ja-JP
best practices
1. Prioritize the use of built-in types
2. Fair use restrictions
3. Plug-in type naming convention
Things to note
oneOf semantics
types: The syntax internally uses JSON Schema's oneOf, which means "exactly matches one of the types".
Performance considerations
Union types verify each type in turn until a match is found. The more types, the greater the performance overhead.
suggestion:
- The number of union types is controlled within 5
- Put the most commonly used types first
Related documents
Version history
- v1.1.0 - First release of cross-type joint validation function
Corresponding sample file
Example entry: union-types.ts
Description: Overrides oneOf generation of types: syntax, string/number unions, and paths for mixing built-in and custom types.