我已经和 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 中的数据库,我认为这将非常简单,但似乎没有那个选项。
你将如何解决这个问题?非常感谢您的帮助!