Express-Validator 项目中的 Schema 验证详解
express-validator 项目地址: https://gitcode.com/gh_mirrors/exp/express-validator
什么是 Schema 验证
在 Express-Validator 项目中,Schema 验证是一种基于对象的验证和清理数据的方式。它允许开发者通过定义清晰的验证规则对象来检查请求数据,相比链式调用方式,Schema 验证提供了更结构化、更易维护的验证方式。
Schema 验证的基本结构
Schema 验证的核心是一个对象,其中每个键代表要验证的字段路径,值是一个包含验证和清理规则的对象。基本结构如下:
{
字段名: {
验证器1: 配置,
验证器2: 配置,
// ...
清理器1: 配置
}
}
常用配置选项详解
1. 字段位置指定
使用 in
属性可以指定字段的位置,可选值包括:
body
:请求体cookies
:Cookiesheaders
:请求头params
:URL 参数query
:查询字符串
id: {
in: ['params', 'query'], // 同时检查 params 和 query
errorMessage: 'ID 错误',
isInt: true
}
2. 错误消息定制
每个验证器都可以通过 errorMessage
属性自定义错误消息:
password: {
isLength: {
errorMessage: '密码长度至少为7个字符',
options: { min: 7 }
}
}
3. 验证器配置
验证器可以接受多种形式的配置:
// 简单配置
isInt: true
// 带选项的配置
isLength: {
options: { min: 7 }
}
// 多个选项的数组配置
rtrim: {
options: [' -'] // 移除右侧空格和连字符
}
4. 清理器使用
清理器可以转换输入数据:
toInt: true, // 转换为整数
customSanitizer: {
options: (value, { req }) => {
return value.trim().toLowerCase()
}
}
高级功能
1. 条件验证
使用 if
属性可以实现条件验证:
someField: {
isInt: {
if: value => value !== '' // 仅当值不为空字符串时验证
}
}
2. 快速失败模式
通过 bail
属性可以在第一个验证失败后停止后续验证:
email: {
isEmail: {
bail: true // 如果邮件格式无效,不再检查其他规则
}
}
3. 嵌套对象验证
使用通配符可以验证嵌套对象或数组:
'addresses.*.postalCode': {
optional: { options: { nullable: true } },
isPostalCode: {
options: 'US' // 验证美国邮编格式
}
}
4. 自定义验证器
可以定义完全自定义的验证逻辑:
custom: {
options: (value, { req, location, path }) => {
// 自定义验证逻辑
return isValid(value)
}
}
实际应用示例
const { checkSchema } = require('express-validator')
const userUpdateSchema = {
id: {
in: ['params'],
isInt: true,
toInt: true,
errorMessage: '无效的用户ID'
},
username: {
isLength: {
options: { min: 3, max: 20 },
errorMessage: '用户名长度应在3-20个字符之间'
},
matches: {
options: /^[a-zA-Z0-9_]+$/,
errorMessage: '用户名只能包含字母、数字和下划线'
}
},
email: {
isEmail: {
bail: true,
errorMessage: '无效的邮箱格式'
},
normalizeEmail: true // 标准化邮箱格式
},
age: {
optional: true,
isInt: {
options: { min: 18, max: 120 },
errorMessage: '年龄应在18-120岁之间'
},
toInt: true
}
}
router.put('/users/:id', checkSchema(userUpdateSchema), (req, res) => {
// 处理验证结果
})
最佳实践
- 模块化设计:将常用的验证 Schema 提取到单独模块中,便于复用
- 清晰的错误消息:为每个验证规则提供明确的错误消息
- 合理使用清理器:在验证前适当清理数据,但注意不要改变业务数据的含义
- 性能考虑:对关键字段使用
bail
选项,避免不必要的验证 - 文档化:为复杂的 Schema 添加注释,说明各字段的验证目的
通过 Schema 验证,Express-Validator 提供了一种声明式、结构化的请求数据验证方式,大大提高了代码的可读性和可维护性。
express-validator 项目地址: https://gitcode.com/gh_mirrors/exp/express-validator
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考