我最近不得不处理类似的问题,并使用了两个节点模块:验证器和 flashify。
在表单视图中,我将表单字段配置如下:
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
注意表单域的命名约定。然后在我的配置文件中设置一个全局变量,它实际上只是表单首次加载时的占位符:
//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});
请注意,此 evenForm 数据被传递回视图,该视图重新填充了默认值。
最后一步是在表单视图中包含 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