用户在节点js中提交后如何显示验证消息错误?

How to show validation message error after user do submission in node js?

即使我输入的值为空,我也无法收到错误消息。它总是 return 我 { first: '', last: '' }。当我输入一些值时,它 return 符合预期。

var express = require('express');
var parser = require('body-parser');
var path = require('path');
var session = require('express-session');
const { check, validationResult } = require('express-validator');
var app = express();
app.set('port',(process.env.PORT || 5000));
app.use(parser.urlencoded({ extended: false }))
app.use(parser.json())

app.use(function(req,res,next){
    res.locals.userValue = null;
    res.locals.errors = null;
    next();
})
app.use(session({
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: true,
    cookie: { maxAge: 60000 }
  }))

app.set('view engine','ejs');
app.set('views',path.join(__dirname,'views'))


app.get('/',function(req,res){
    res.render('home',{
        topicHead : 'Student Form'
    });
    console.log('user accessing Home page');
});
app.post('/student/add',function(req,res){
    let fname = req.body.fname
    let lname = req.body.lname
    // Check Input Field
    check('fname','Name is required').not().isEmpty(),
    check('lname','Name is required').not().isEmpty()
    const result= validationResult(req);
    var errors = result.errors;

  if (!result) {
  //response validate data to register.ejs
     res.render('home', {
      errors: errors
    })
    console.log('Error');
  }
  else{
    var student = {
        first : fname,
        last : lname
    }
    console.log(student);
    res.render('home',{
        userValue : student,
        topicHead : 'Student Form'
    });
    console.log('OK');
  }  
});
app.listen(app.get('port'),function(){
    console.log('server running on port '+app.get('port'));
})


<body>
    <form name="form1" method="POST" action="/student/add">
    <table>
        <tr>
        <td>First name</td>
        <td><input type="text" name="fname" ></td>
        </tr>
        <tr>
        <td>last name</td>
        <td><input type="text" name="lname" ></td>
        </tr>
        <tr>
        <td colspan="2"><input type="submit" value="Save" ></td>
        </tr>
    </table>
    </form>
    <% if (locals.errors) { %>
        <ul>
            <% Object.values(errors).forEach(function(error){ %>
                  <li><%= error.msg %></li>
            <% }); %>
        </ul>
        <% } %>
</body>

我希望输出显示错误消息而不是 { first: '', last: '' } 并且应该显示错误控制台日志而不是显示 OK 控制台日志

根据 express-validator 文档,检查似乎以错误的方式使用。 https://express-validator.github.io/docs/index.html

下面的代码片段应该可以解决问题。

   app.post('/student/add',[
    check('fname','Name is required').not().isEmpty(),
    check('lname','Name is required').not().isEmpty()
  ],function(req,res){
    // Check Input Field

    const result= validationResult(req);
    var errors = result.errors;

    let fname = req.body.fname
    let lname = req.body.lname
  if (!result) {
  //response validate data to register.ejs
     res.render('home', {
      errors: errors
    })
    console.log('Error');
  }
  else{
    var student = {
        first : fname,
        last : lname
    }
    console.log(student);
    res.render('home',{
        userValue : student,
        topicHead : 'Student Form'
    });
    console.log('OK');
  }  
});