重要前提
安装AI Skills的关键前提是:必须科学上网,且开启TUN模式,这一点至关重要,直接决定安装能否顺利完成,在此郑重提醒三遍:科学上网,科学上网,科学上网。查看完整安装教程 →
custom-format-validators by zaggino/z-schema
npx skills add https://github.com/zaggino/z-schema --skill custom-format-validatorsJSON Schema 的 format 用于对字符串(或其他类型)的值施加超出基本类型检查的约束。z-schema 包含内置的验证器,并支持注册自定义验证器——包括同步和异步两种。
z-schema 内置了所有标准 JSON Schema 格式的验证器:
| 格式 | 验证内容 |
|---|---|
date | RFC 3339 完整日期 (2024-01-15) |
date-time | RFC 3339 日期时间 (2024-01-15T09:30:00Z) |
time | RFC 3339 时间 () |
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
09:30:00Zemail | RFC 5321 电子邮件地址 |
idn-email | 国际化电子邮件 |
hostname | RFC 1123 主机名 |
idn-hostname | 国际化主机名 |
ipv4 | IPv4 地址 |
ipv6 | IPv6 地址 |
uri | RFC 3986 URI |
uri-reference | URI 或相对引用 |
uri-template | RFC 6570 URI 模板 |
iri | 国际化 URI |
iri-reference | 国际化 URI 引用 |
json-pointer | RFC 6901 JSON 指针 |
relative-json-pointer | 相对 JSON 指针 |
regex | ECMA-262 正则表达式 |
duration | ISO 8601 持续时间 |
uuid | RFC 4122 UUID |
格式验证器是一个函数 (input: unknown) => boolean。如果有效则返回 true,无效则返回 false。对于不适用类型的输入(例如,当输入不是字符串时)返回 true——z-schema 会为任何值类型调用格式验证器。
import ZSchema from 'z-schema';
ZSchema.registerFormat('postal-code', (value) => {
if (typeof value !== 'string') return true; // 跳过非字符串
return /^\d{5}(-\d{4})?$/.test(value);
});
const validator = ZSchema.create();
validator.registerFormat('postal-code', (value) => {
if (typeof value !== 'string') return true;
return /^\d{5}(-\d{4})?$/.test(value);
});
实例格式会覆盖同名的全局格式。
const validator = ZSchema.create({
customFormats: {
'postal-code': (value) => typeof value === 'string' && /^\d{5}(-\d{4})?$/.test(value),
'always-valid': () => true,
'disable-email': null, // 禁用内置的电子邮件验证器
},
});
传递 null 可以禁用内置的或全局注册的格式。
返回 Promise<boolean>。验证器必须使用 { async: true } 选项创建。
const validator = ZSchema.create({ async: true });
validator.registerFormat('user-exists', async (value) => {
if (typeof value !== 'number') return true;
const user = await db.findUser(value);
return user != null;
});
// 验证(返回 Promise)
try {
await validator.validate(data, schema);
} catch (err) {
console.log(err.details);
}
异步格式验证器在 asyncTimeout 毫秒(默认值:2000)后超时。对于慢速操作可以增加此值:
const validator = ZSchema.create({
async: true,
asyncTimeout: 10000, // 10 秒
});
超时的验证器会产生一个 ASYNC_TIMEOUT 错误。
JSON Schema 规范在新草案中改变了 format 的工作方式:
| 草案 | 默认行为 | 使用 formatAssertions: true 时 |
|---|---|---|
| draft-04/06/07 | 始终断言(不匹配则失败) | 始终断言 |
| draft-2019-09 | 始终断言(z-schema 默认) | 仅作注解,除非启用了词汇表 |
| draft-2020-12 | 始终断言(z-schema 默认) | 仅作注解,除非启用了词汇表 |
z-schema 默认 formatAssertions: null(旧版行为——始终断言)。要遵循现代草案中规范要求的词汇表感知行为:
const validator = ZSchema.create({ formatAssertions: true });
要禁用所有格式断言(仅作注解):
const validator = ZSchema.create({ formatAssertions: false });
默认情况下,对于 draft-04/06/07 中无法识别的格式名称,z-schema 会报告 UNKNOWN_FORMAT。现代草案(2019-09, 2020-12)总是静默忽略未知格式。
要在旧草案中抑制未知格式错误:
const validator = ZSchema.create({ ignoreUnknownFormats: true });
// 全局
ZSchema.unregisterFormat('postal-code');
// 实例
validator.unregisterFormat('postal-code');
// 列出全局注册的自定义格式
const customFormats = ZSchema.getRegisteredFormats();
// 列出实例上所有支持的格式(内置 + 自定义)
const allFormats = validator.getSupportedFormats();
// 检查是否支持特定格式
const supported = validator.isFormatSupported('postal-code');
ZSchema.registerFormat('phone', (value) => {
if (typeof value !== 'string') return true;
return /^\+?[1-9]\d{1,14}$/.test(value); // E.164 格式
});
ZSchema.registerFormat('iso-date', (value) => {
if (typeof value !== 'string') return true;
const d = new Date(value);
return !isNaN(d.getTime()) && value === d.toISOString().split('T')[0];
});
const validator = ZSchema.create({ async: true });
validator.registerFormat('valid-country', async (value) => {
if (typeof value !== 'string') return true;
const countries = await fetchValidCountries();
return countries.includes(value.toUpperCase());
});
格式验证器可以修改对象(谨慎使用):
ZSchema.registerFormat('fill-defaults', (obj) => {
if (typeof obj === 'object' && obj !== null) {
(obj as Record<string, unknown>).createdAt ??= new Date().toISOString();
}
return true;
});
{
"type": "object",
"properties": {
"phone": { "type": "string", "format": "phone" },
"country": { "type": "string", "format": "valid-country" },
"zipCode": { "type": "string", "format": "postal-code" }
}
}
每周安装量
54
代码仓库
GitHub 星标数
342
首次出现
2026年2月27日
安全审计
安装于
github-copilot54
openclaw12
gemini-cli12
codex12
kimi-cli12
cursor12
JSON Schema format constrains string (or other) values beyond basic type checking. z-schema includes built-in validators and supports registering custom ones — both sync and async.
z-schema ships with validators for all standard JSON Schema formats:
| Format | Validates |
|---|---|
date | RFC 3339 full-date (2024-01-15) |
date-time | RFC 3339 date-time (2024-01-15T09:30:00Z) |
time | RFC 3339 time (09:30:00Z) |
email | RFC 5321 email address |
idn-email | Internationalized email |
hostname | RFC 1123 hostname |
idn-hostname | Internationalized hostname |
ipv4 | IPv4 address |
ipv6 | IPv6 address |
uri | RFC 3986 URI |
uri-reference | URI or relative reference |
uri-template | RFC 6570 URI template |
iri | Internationalized URI |
iri-reference | Internationalized URI reference |
json-pointer | RFC 6901 JSON Pointer |
relative-json-pointer | Relative JSON Pointer |
regex | ECMA-262 regex |
duration | ISO 8601 duration |
uuid | RFC 4122 UUID |
A format validator is a function (input: unknown) => boolean. Return true if valid, false if invalid. Return true for non-applicable types (e.g., when input is not a string) — z-schema calls format validators for any value type.
import ZSchema from 'z-schema';
ZSchema.registerFormat('postal-code', (value) => {
if (typeof value !== 'string') return true; // skip non-strings
return /^\d{5}(-\d{4})?$/.test(value);
});
const validator = ZSchema.create();
validator.registerFormat('postal-code', (value) => {
if (typeof value !== 'string') return true;
return /^\d{5}(-\d{4})?$/.test(value);
});
Instance formats override global formats with the same name.
const validator = ZSchema.create({
customFormats: {
'postal-code': (value) => typeof value === 'string' && /^\d{5}(-\d{4})?$/.test(value),
'always-valid': () => true,
'disable-email': null, // disable the built-in email validator
},
});
Pass null to disable a built-in or globally registered format.
Return Promise<boolean>. The validator must be created with { async: true }.
const validator = ZSchema.create({ async: true });
validator.registerFormat('user-exists', async (value) => {
if (typeof value !== 'number') return true;
const user = await db.findUser(value);
return user != null;
});
// Validate (returns Promise)
try {
await validator.validate(data, schema);
} catch (err) {
console.log(err.details);
}
Async format validators time out after asyncTimeout milliseconds (default: 2000). Increase for slow operations:
const validator = ZSchema.create({
async: true,
asyncTimeout: 10000, // 10 seconds
});
Timed-out validators produce an ASYNC_TIMEOUT error.
The JSON Schema spec changed how format works in newer drafts:
| Draft | Default behavior | With formatAssertions: true |
|---|---|---|
| draft-04/06/07 | Always asserts (fails on mismatch) | Always asserts |
| draft-2019-09 | Always asserts (z-schema default) | Annotation-only unless vocabulary enabled |
| draft-2020-12 | Always asserts (z-schema default) | Annotation-only unless vocabulary enabled |
z-schema defaults to formatAssertions: null (legacy — always assert). To respect the spec's vocabulary-aware behavior for modern drafts:
const validator = ZSchema.create({ formatAssertions: true });
To disable all format assertions (annotation-only):
const validator = ZSchema.create({ formatAssertions: false });
By default, z-schema reports UNKNOWN_FORMAT for unrecognized format names in draft-04/06/07. Modern drafts (2019-09, 2020-12) always silently ignore unknown formats.
To suppress unknown format errors in older drafts:
const validator = ZSchema.create({ ignoreUnknownFormats: true });
// Global
ZSchema.unregisterFormat('postal-code');
// Instance
validator.unregisterFormat('postal-code');
// List globally registered custom formats
const customFormats = ZSchema.getRegisteredFormats();
// List all supported formats (built-in + custom) on an instance
const allFormats = validator.getSupportedFormats();
// Check if a specific format is supported
const supported = validator.isFormatSupported('postal-code');
ZSchema.registerFormat('phone', (value) => {
if (typeof value !== 'string') return true;
return /^\+?[1-9]\d{1,14}$/.test(value); // E.164 format
});
ZSchema.registerFormat('iso-date', (value) => {
if (typeof value !== 'string') return true;
const d = new Date(value);
return !isNaN(d.getTime()) && value === d.toISOString().split('T')[0];
});
const validator = ZSchema.create({ async: true });
validator.registerFormat('valid-country', async (value) => {
if (typeof value !== 'string') return true;
const countries = await fetchValidCountries();
return countries.includes(value.toUpperCase());
});
Format validators can mutate objects (use with caution):
ZSchema.registerFormat('fill-defaults', (obj) => {
if (typeof obj === 'object' && obj !== null) {
(obj as Record<string, unknown>).createdAt ??= new Date().toISOString();
}
return true;
});
{
"type": "object",
"properties": {
"phone": { "type": "string", "format": "phone" },
"country": { "type": "string", "format": "valid-country" },
"zipCode": { "type": "string", "format": "postal-code" }
}
}
Weekly Installs
54
Repository
GitHub Stars
342
First Seen
Feb 27, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
github-copilot54
openclaw12
gemini-cli12
codex12
kimi-cli12
cursor12
agent-browser 浏览器自动化工具 - Vercel Labs 命令行网页操作与测试
172,600 周安装