最近、同様の問題に取り組む必要があり、validator と flashify の 2 つのノード モジュールを使用しました。
フォーム ビューで、フォーム フィールドを次のように構成しました。
div.control-group
label.control-label Description
div.controls
textarea(name='eventForm[desc]', id='desc', rows='3').input-xxlarge= eventForm.desc
div.control-group
label.control-label Tag
div.controls
select(id='tag', name='eventForm[tag]')
tags = ['Medjugorje', 'Kibeho', 'Lourdes', 'Fatima']
for tag in tags
option(selected=eventForm.tag == tag)= tag
フォーム フィールドの命名規則に注意してください。次に、構成ファイルで 1 つのグローバル変数を設定します。これは、フォームが最初に読み込まれたときの単なるプレースホルダーです。
//locals
app.locals.eventForm = []; // placeholder for event form repopulation
検証ロジックは私のルーター ファイルにあり、次のようになります。
app.post('/posts', function(req, res){
var formData = req.body.eventForm;
var Post = models.events;
var post = new Post();
post.text = formData.desc;
post.tag = formData.tag;
// run validations before saving
var v = new Validator();
var isPostValid = true;
// custom error catcher for validator, which uses flashify
v.error = function(msg) {
res.flash('error', msg);
isPostValid = false;
}
v.check(post.text, "Description field cannot be empty").notEmpty();
v.check(post.tag, "Tag field cannot be empty").notEmpty();
次に、エラーがあるかどうかを確認し、エラーがある場合は、フォーム データをビューに戻します。
// reject it
res.render('Event.jade', {page: req.session.page, eventForm: formData});
この eventForm データがビューに戻され、デフォルト値が再入力されることに注意してください。
最後のステップは、flashify コンポーネントをフォーム ビューに含めることです。
div(style='margin-top: 60px').container-fluid
include flashify
flashify ビューのコードは次のようになります。
if (flash.error != undefined)
div.container
div.alert.alert-error
b Oops!
button(type='button', data-dismiss='alert').close ×
ul
each error in flash.error
li= error
if (flash.success != undefined)
div.container
div.alert.alert-success
b Success!
button(type='button', data-dismiss='alert').close ×
ul
each success in flash.success
li= success