egg-fish-validate
v0.1.3
Published
egg数据校验插件
Downloads
41
Readme
egg-fish-validate
安装
$ npm i egg-fish-validate --save
依赖说明
依赖的 egg 版本
| egg-fish-validate 版本 | egg 1.x | | ---------------------- | ------- | | 1.x | 😁 | | 0.x | ❌ |
开启插件
// config/plugin.js
exports.fishValidate = {
enable: true,
package: "egg-fish-validate",
};
使用方法
rules 校验规则 (必传)
data 校验数据集 (可选) ,默认集合 params,queries,body
mergeError 是否合并异常后抛出(可选) 默认 true
ctx.validate(rules[,data])
示例
const rules = {
id: "int",
name: "string?", // 字符串类型(可选)
sex: [0, 1, 2], // 枚举类型
sex2: "0|1|2?", // 枚举类型(可选)
endTime: "datetime",
endDt: "date",
other: "?", // 任意值(可选)
};
const data = {
id: "a135",
sex: 1,
endTime: "2020-05-02 12:01:04",
endDt: "1991",
};
ctx.validate(rules, data, true);
# 第二参数为Boolean时,则data为默认值,mergeError = Boolean
ctx.validate(rules, true);
如果验证失败,会返回:
HTTP/1.1 422 Unprocessable Entity
{ code: 'invalid_param',
message: 'Validation Failed',
errors:[
{ code: 'invalid',
field: 'id',
message: 'should be an int',
value: 'a135'
},
{ code: 'invalid',
field: 'endDt',
message: 'should be a date',
value: '1991'
}
]
}
数组字段
v0.1.0
新增数组结构数据支持,ruleSet
新增isArray
属性示例
const rules = {
id: "[int]", // int array, required
name: { required: false, type: "string", isArray: true }, // ruleSet写法
sex: "[0|1|2]", // 枚举类型数组
sex2: "[0|1|2]?", // 枚举类型数组(可选)
endDt: "[date]",
other: "[]", // 任意类型数组数据
};
// 符合要求的数据示例
const data = {
id: [1, 2, 3],
sex: ["0"],
sex2: [], // 空数组会被视为空数据
endDt: ["2020-12-12"],
other: ["other"],
};
const result = ctx.validate(rules, data, true);
// 结果数据
// {
// id: [1,2,3],
// name: undefined,
// sex: ["0"],
// sex2: undefined,
// endDt: [2020-12-12T00:00:00.000Z],
// other: ["other"],
// }
内置规则
?
表示可选
| 规则类型 | 说明 |
| ---------- | ---------------------------- |
| string
| 字符串 |
| int
| 整数 |
| double
| 小数 |
| number
| 数值 |
| date
| 日期 yyyy-MM-dd |
| datetime
| 日期时间 yyyy-MM-dd HH:mm:ss |
| tel
| 手机号 |
| email
| 邮箱 |
| enmu
| 枚举 |
| any
| 任意 |
高级用法
- 使用规则对象
ruleSet
const rule = {
required: true, // 是否必填
format: (value, ruleSet) => value > 1, // 格式校验器,支持:正则表达式 或者 校验函数
type: "int", // 规则类型,自定义格式校验器后,不需要此参数
options: [], // 枚举类型的可选项
convert: (value, ruleSet) => Number(value), // 数据格式转换函数
message: "数值必须大于1", // 覆盖默认的校验失败提醒消息
default: 10, // 默认值
isArray: false, // 是否为数组结构数据,默认false
rename: "userId", // 重命名字段 {id: 1} -> {userId: 1}
};
const params = ctx.validate({ id: rule });
详细配置
// config/config.default.js
exports.fishValidate = {
customMatchRules: {}, // 自定义匹配规则
throwError: true, // 抛出异常
convert: true, // 按rules目标类型转换数据类型(参数数据大部分都是string)
trim: true, // string类型数据去除首尾空格
};
版本更新日志
v0.1.3
- 支持 object 数据检查
- "" 空字符串默认为 any
v0.1.0
- 支持数组结构数据
- 支持重写参数名