我为 Sails 1.x 中的验证创建了一个小帮助钩子:
https://github.com/xtrinch/sails-hook-validation-ev
在使用蓝图路由的最简单形式中,它通过向模型添加验证函数来工作:
Todo.js:
module.exports = {
attributes: {
title: {
type: 'string',
required: true
},
description: {
type: 'string',
required: true
},
},
validate: (req) => {
req.check('title')
.exists()
.isLength({ min: 1 }).withMessage('must be at least 5 chars long');
req.check('description').exists();
}
};
示例响应:
{
"errors": [
{
"location": "params",
"param": "title",
"msg": "Invalid value"
},
{
"location": "params",
"param": "title",
"msg": "must be at least 5 chars long"
}
]
}
检查 API 取自 express-validator,以免重新发明轮子。
有关更多选项和高级用法,请参阅完整的钩子readme.md。