Express-Validator 6.0.0 中的Schema验证详解
express-validator 项目地址: https://gitcode.com/gh_mirrors/exp/express-validator
什么是Schema验证
Schema验证是express-validator提供的一种基于对象结构的验证方式,它允许开发者以更结构化、更清晰的方式定义请求参数的验证规则和清理规则。相比传统的链式调用方式,Schema验证更适合处理复杂的数据结构,特别是当需要验证多个字段或嵌套对象时。
Schema验证的基本结构
Schema验证的基本结构是一个JavaScript对象,其中:
- 键(key)表示要验证的字段路径
- 值(value)是一个包含验证规则和清理规则的对象
每个字段的验证对象可以包含以下类型的配置:
- 字段位置(in):指定字段在请求中的位置
- 验证器(validator):定义字段需要满足的条件
- 清理器(sanitizer):定义如何清理字段值
- 错误信息(errorMessage):自定义验证失败时的错误提示
- 可选性(optional):定义字段是否为可选
Schema验证的核心功能详解
1. 字段位置定义
通过in
属性可以指定字段在请求中的位置,可选值包括:
body
:请求体cookies
:Cookiesheaders
:请求头params
:URL参数query
:查询字符串
如果不指定in
属性,则会在所有位置检查该字段。
id: {
in: ['params', 'query'], // 在params和query中查找id字段
errorMessage: 'ID is wrong',
isInt: true,
toInt: true
}
2. 内置验证器使用
express-validator提供了多种内置验证器,可以直接在Schema中使用:
password: {
isLength: {
errorMessage: 'Password should be at least 7 chars long',
options: { min: 7 } // 密码至少7个字符
}
},
firstName: {
isUppercase: {
negated: true, // 验证名字不是全大写
}
}
3. 自定义验证器和清理器
当内置验证器不能满足需求时,可以使用自定义验证器和清理器:
myCustomField: {
// 自定义验证器
custom: {
options: (value, { req, location, path }) => {
return value + req.body.foo + location + path;
}
},
// 自定义清理器
customSanitizer: {
options: (value, { req, location, path }) => {
let sanitizedValue;
if (req.body.foo && location && path) {
sanitizedValue = parseInt(value);
} else {
sanitizedValue = 0;
}
return sanitizedValue;
}
}
}
4. 嵌套对象和数组验证
Schema验证支持通过通配符*
和点号.
来验证嵌套对象和数组:
'addresses.*.postalCode': {
optional: { options: { nullable: true } }, // 允许为null或undefined
isPostalCode: true // 验证邮编格式
}
5. 清理器使用
清理器可以在验证前对数据进行处理:
firstName: {
rtrim: {
options: [' -'], // 移除右侧空格和破折号
}
}
Schema验证的最佳实践
- 合理组织Schema结构:将相关字段的验证规则组织在一起,提高代码可读性
- 使用明确的错误信息:为每个验证规则提供清晰的错误提示
- 区分必填和可选字段:明确标记哪些字段是必须的,哪些是可选的
- 合理使用嵌套验证:对于复杂数据结构,使用嵌套验证保持代码整洁
- 组合使用验证和清理:先清理数据再验证,确保验证的准确性
实际应用示例
以下是一个完整的用户注册Schema验证示例:
const { checkSchema } = require('express-validator');
const userRegistrationSchema = {
username: {
isLength: {
options: { min: 3, max: 20 },
errorMessage: '用户名长度应在3-20个字符之间'
},
matches: {
options: /^[a-zA-Z0-9_]+$/,
errorMessage: '用户名只能包含字母、数字和下划线'
}
},
email: {
isEmail: {
errorMessage: '请输入有效的邮箱地址'
},
normalizeEmail: true // 标准化邮箱格式
},
password: {
isLength: {
options: { min: 8 },
errorMessage: '密码至少需要8个字符'
},
matches: {
options: /[A-Z]/,
errorMessage: '密码必须包含至少一个大写字母'
}
},
'profile.age': {
optional: true,
isInt: {
options: { min: 18 },
errorMessage: '年龄必须大于18岁'
},
toInt: true
},
'addresses.*.zipCode': {
isPostalCode: {
options: 'any',
errorMessage: '请输入有效的邮编'
}
}
};
app.post('/register', checkSchema(userRegistrationSchema), (req, res) => {
// 处理注册逻辑
});
通过Schema验证,我们可以清晰地定义所有验证规则,使代码更易于维护和理解。express-validator的Schema验证功能强大而灵活,能够满足大多数Web应用的数据验证需求。
express-validator 项目地址: https://gitcode.com/gh_mirrors/exp/express-validator
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考