0

I am not able to get the error message even though the value that i inputted is empty. It always return me { first: '', last: '' }. While i inputted some values, it returns as expected.

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>

I expect the output is show the error message instead of { first: '', last: '' } and Error console log should be display instead OK console log displayed

1
  • what is your validationResult function? Commented Aug 18, 2019 at 6:20

1 Answer 1

1

As per express-validator documentation, It looks like check is used in the wrong way. https://express-validator.github.io/docs/index.html

Below code snippet should solve the issue.

   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');
  }  
});
Sign up to request clarification or add additional context in comments.

1 Comment

It solved by change the !result into errors and it will print out the error message. Thank you so much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.