Schema 数据校验(AJV)
灵感:能力工具箱 ajv-schema(pkg: ajv)。
在保存/导入客户 JSON 前,用 JSON Schema + AJV 做本地校验,返回可读中文错误列表。
何时使用
- 导入客户 JSON / 接口载荷自检
- 动态表单提交前结构校验
硬约束
- 使用
ajv(建议 Ajv2020 或项目既有大版本,文档写明)。 - Schema 与数据均为纯 JSON;校验失败返回
errors[](路径 + 信息),禁止只抛英文堆栈。 - 常见规则示例:必填
name、mobile模式、枚举阶段等;可替换业务 Schema。 allErrors: true以便一次列出多处问题(可配置)。- 不发起网络请求;Schema 内
$ref远程地址默认禁用或明确警告。
推荐实现要点
import Ajv from 'ajv'
const ajv = new Ajv({ allErrors: true, strict: false })
export const customerSchema = {
type: 'object',
additionalProperties: true,
required: ['name'],
properties: {
name: { type: 'string', minLength: 1 },
mobile: { type: 'string', pattern: '^1\\d{10}$' },
stage: { type: 'string', enum: ['lead', 'contact', 'intend', 'negotiate', 'won', 'lost'] },
},
} as const
export function validateCustomer(data: unknown) {
const validate = ajv.compile(customerSchema)
const ok = validate(data)
if (ok) return { ok: true as const, errors: [] as string[] }
const errors = (validate.errors || []).map((e) => {
const path = e.instancePath || '/'
return `${path} ${e.message || 'invalid'}`
})
return { ok: false as const, errors }
}
Agent 步骤
- 接入 AJV + 业务 Schema;错误文案可映射中文。
- 自测:缺 name、错误手机号应失败;合法对象通过。
- UI:错误列表贴近字段展示。
附加
- README.md · reference.md · templates/usage.md