One field supports multiple types
Use .pattern() method to match multiple formats
⚠️ This document describes the method of "matching multiple formats with the same string field".
If you need true union semantics across underlying types, such as string | number | null, please use types: syntax in preference.
Basic usage
Description:
- Use
|in regular expressions to represent "or", and brackets()to group - Use
.messages()to set error messages and support multiple languages
Common examples
User login (username or email)
Contact information (email or mobile phone number)
URL (http or https)
Support multiple languages
Built-in multi-language key:
pattern.emailOrPhone- Email or mobile phone numberpattern.usernameOrEmail- username or emailpattern.httpOrHttps- http or https URL
Regular expression quick check
Complete example
Output:
Corresponding sample file
Example entry: union-type-guide.ts
Description: Shows the "single string field matching multiple formats" solution based on .pattern(), and the corresponding error messages in Chinese and English.