【发布时间】:2014-03-23 01:12:36
【问题描述】:
我玩 Sails 大概有一天了。我正在努力思考什么是在 Sails.js 中进行广泛验证的最佳方式。
这里是场景:
Registration Form:
Username: _______________
E-Mail: _______________
Password: _______________
Confirm: _______________
用户输入:
- 正确的电子邮件
- 已经存在的用户名
- 两个不匹配的密码
期望的结果:
Username: _______________ x Already taken
E-Mail: _______________ ✓
Password: _______________ ✓
Confirm: _______________ x Does not match
要求,几个关键点:
- 用户会收到所有错误消息(不仅仅是第一条),以了解其输入的各个方面。它们不模糊(“用户名已被占用”或“用户名必须至少有 4 个字母长”优于“无效用户名”)
- 内置模型验证显然不能负责检查匹配的密码确认 (SRP)
我认为我需要做的事情:
用户控制器:
create: function(req, res) {
try {
// use a UserManager-Service to keep the controller nice and thin
UserManager.create(req.params.all(), function(user) {
res.send(user.toJSON());
});
}
catch (e) {
res.send(e);
}
}
用户管理器:
create: function(input, cb) {
UserValidator.validate(input); // this can throw a ValidationException which will then be handled by the controller
User.create(input, cb); // this line should only be reached if the UserValidator did not throw an exception
}
用户:(模型)
attributes: {
username: {
type: 'string',
required: true,
minLength: 3,
unique: true
},
email: {
type: 'email',
required: true,
unique: true
},
password: {
type: 'string',
required: true
}
}
用户验证器:
这是棘手的部分。我需要将特定于输入的验证(密码确认是否匹配?)与模型验证(用户名是否被采用,电子邮件地址是否有效?)结合起来。
如果有办法实例化用户模型并执行验证而不保存到 Sails/Waterline 中的数据库,我认为这将非常简单,但似乎没有那个选项。
您将如何解决这个问题?非常感谢您的帮助!
【问题讨论】:
标签: node.js validation orm sails.js waterline