【问题标题】:Form validation and displaying error message using ejs使用 ejs 进行表单验证和显示错误消息
【发布时间】:2019-02-19 20:27:42
【问题描述】:

我是 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');

}); 

【问题讨论】:

  • 首先,您需要清理输入(不允许任何 XSS 攻击)。电子邮件 - 使用正则表达式检查,年龄 - 检查它是否是数字,密码是否存储为字符串,名称 - 检查是否没有任何脚本标签等 - 您可以在谷歌搜索或在 stackoverflow 上搜索后找到所有这些。 :)
  • 你的问题太宽泛了。您需要添加更多详细信息,例如验证哪些字段以及基于什么?需求?长度?
  • 例如 - 这是一个与使用正则表达式进行电子邮件验证相关的好线程:stackoverflow.com/questions/46155/…
  • @AnkitAgarwal :我只想如果我提交空白表单然后应该显示错误消息,我如何将错误传递给查看(ejs)并显示错误?
  • @sheetaldhiman 我建议你看看这个npmjs.com/package/form-validate

标签: javascript node.js express ejs


【解决方案1】:

您可以使用 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/

sending flash message in express

【讨论】:

    【解决方案2】:

    您必须首先在客户端处理此问题,因此如果客户端单击提交按钮,您必须检查一切是否正常(所有必填字段均填写明显正确的值(日期、电子邮件、电话号码、.. .)) 然后你将数据发送到服务器。

    EJS 与表单验证无关,它在浏览器上使用 jQuery 或纯 JS 处理。

    当然,在服务器端,您会在访问数据库或任何其他操作之前检查这些值

    【讨论】:

      猜你喜欢
      • 2019-12-10
      • 2019-06-11
      • 2016-03-05
      • 1970-01-01
      • 2022-11-09
      • 2021-03-29
      • 1970-01-01
      • 2018-12-16
      • 1970-01-01
      相关资源
      最近更新 更多