1

I am trying to validate a form data using express validator. I have routes and controllers in separate files. I want to retain the data in the form fields after the validation has failed. I am using express validator to do the validation. Here is some code I wrote

router.js

const express = require('express');
const router = express.Router();
const adminController = require('../controllers/adminController');
const { check } = require('express-validator');

router.all('/*',(req,res,next) => {
  req.app.locals.layout = 'admin';
  next();
});

router.route('/')
  .get(adminController.index);

router.route('/news-upload')
  .get(adminController.getNews)
  .post([check('title', 'Title cannot be empty').not().isEmpty(),
     check('description', 'Content cannot be empty!').not().isEmpty()],
     adminController.submitNews);

module.exports = router;

controller.js

submitNews: (req, res) => {
    let error = validationResult(req);

    if (!error.isEmpty()) {
        res.render('admin/news', {
            title: req.body.title,
            description: req.body.description,
            error_message: error.errors[0].msg

        });
    }
    else {----
         }

news.handlebars

<div class = "container">
<h1>Create New Post</h1>

<div class="row p-4">
    <div class="col-md-10">
        <form action="/admin/news-upload" method="post">
        <div class="form-group">
            <lebel for="title">Title</lebel>
            <input type="text" class="form-control" name="title" id="title" 
placeholder="Enter The Title">
        </div>
        <div class="form-group">
            <label for="description">Content</label>
            <textarea name="description" id="description" class="form- 
control" placeholder="Enter your content here" rows="10"></textarea>
        </div>
        <button class="btn btn-outline-success btn-lg" type="submit">Create 
Post</button>

        </form>


    </div>
</div>
</div>

I am using connect-flash to display the messages. Here you can see

title: req.body.title
description: req.body.description 
error_message: error.errors[0].msg

I am trying to get the form values and send it back via res.render but this is not working. I get the flash messages which means error_message: error.errors[0].msg works and validation works perfectly but I am trying to retain the values of the form fields. How can I accomplish that if not like above? Also I am using handlebars as my view engine. Thank you.

Drilldoge
  • 83
  • 7

1 Answers1

0

I thought passing form name: req.body.name would automatically set the value. I could't be more wrong. You have to use it {{name}} in the handlebars file aswell. Thank you!!

Drilldoge
  • 83
  • 7