私はおそらく1日くらいSailsをいじっています。私は、Sails.js で広範な検証を行うための最良の方法について頭を悩ませようとしています。
シナリオは次のとおりです。
Registration Form:
Username: _______________
E-Mail: _______________
Password: _______________
Confirm: _______________
ユーザー入力:
- 正しいメール
- すでに存在するユーザー名
- 一致しない 2 つのパスワード
望ましい結果:
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 のデータベースに保存せずに検証を実行する方法があれば、これは非常に簡単だと思いますが、そのオプションはないようです。
この問題をどのように解決しますか?ご助力ありがとうございます!