首页 > 解决方案 > 使用 ejs 进行表单验证和显示错误消息

问题描述

我是 nodejs 的新手,我正在尝试使用 express js 中的 ejs 模板验证我的表单。如何验证表单条目并在验证失败时显示错误消息?

这是我的服务器代码:

app.post('/formsubmit', function(req, res) 
    {
            console.log(req.body);
            var name =req.body.name;
            var email=req.body.email;
            var pwd =req.body.pwd;
            var age =req.body.age;

            var con = mysql.createConnection
                ({
                      host: "localhost",
                      user: "root",
                      password: "",
                      database: "demos"
                });

            con.connect(function(err) {
            if (err) throw err;
              console.log("Connected!");
              var sql = "INSERT INTO student (name, email,age) VALUES ('"+name+"','"+email+"','"+age+"')";
              con.query(sql, function (err, result) 
                {
                    if (err) throw err;
                     console.log("1 record inserted");
              });
            });             

        //console.log(record);
            res.send('Record Inserted Successfully');

}); 

标签: javascriptnode.jsexpressejs

解决方案


您可以使用 express-validator 验证表单并使用 connect-flash 发送 flash 消息。

const { check, validationResult } = require('express-validator/check');

app.post('/formsubmit', [check('title').not().isEmpty(),
                    check('content').not().isEmpty(),
                    check('title').not().isEmpty(),
                    check('content').not().isEmpty()]
                    ,function(req, res) {

            const errors = validationResult(req);
            if (!errors.isEmpty()) {
                req.flash('error', "Provide details for the blog");
                res.redirect('/notes');
            }
            else
            {
                //perform required operation
                res.send();
            }

}); 

将这些添加到您的 app.js

var flash = require('connect-flash');
app.use(flash()); // flash messages

app.use(function (req, res, next) {
    res.locals.success = req.flash('success');
    res.locals.info = req.flash('info');
    res.locals.error = req.flash('error');
    res.locals.user = req.user || null;
    next();
  });

请参阅此链接以了解 express-validator 和 flash 消息

https://express-validator.github.io/docs/

以快递方式发送闪信


推荐阅读