egg-validate
基于 JSON Schema + AJV 的校验中间件,致力于:
- 前后端公用校验规则
- 保证前后端校验一致
- 减少规则编写成本
依赖说明
依赖的 egg 版本
egg-validate 版本 | egg 1.x |
---|---|
1.x | 😁 |
0.x | ❌ |
依赖的插件
开启插件
// config/plugin.jsexportsvalidate = enable: true package: 'egg-validate';
方式
服务器端
中间件校验处理
// router// 在需要校验处理的路由,开启中间件,中间件会自己校验,如果校验失败,返回失败信息module { const router controller = app const validator = appmiddleware router}
// /app/validate/test.json
// 错误信息http // response success: false errors: ... message: "手机不能为空"
Controller自己处理错误
接上栗
// home Controllerasync if bodyformValidate return success: true message: '手机是必填项哦' http // response success: true message: '手机是必填项哦'
浏览器端
请求 Schema
exportsvalidateSchema = uri: '/api/schema' // 配置项,指定了通过请求schema路由 axios
详细配置
请到 config/config.default.js 查看详细配置项说明。
单元测试
提问交流
请到 egg issues 异步交流。