javascript - 使用 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');
});
解决方案
您可以使用 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 消息
推荐阅读
- bash - 如何将多个 Ansible 变量添加到 csv 文件的单行中?
- dll - 有没有办法让我的 .NET Blazor WASM 应用程序不被大多数防火墙阻止?
- vue.js - 如何解决测试用例 vue 测试工具中的工具提示警告?
- html - 如何将微型 mce 图像源从远程 Web 服务器更改为本地服务器目录
- java - 使用 Micornaut 和 swagger 的 Codegen 错误
- node.js - 通过节点firebase-admin发送push时,push不来IOS的现象
- python - 在heroku中通过pipenv从git安装
- python - Python - CSV 文件中的列包含多个分隔符和结果
- python - 是否有与 Python 的 itertools.combinations 等效的 Go?
- mysql - 在 laravel 中更新时如何优化查询原始?