Saheed Olayiwola
Saheed Olayiwola

Reputation: 13

How to use express validator

i need validator to check for error and log into console if any

here is my code below;

const expressValidator = require('express-validator');
const { check, validationResult } = require('express-validator/check');
const router = express.Router();

router.post('/add-page', function(req, res){
check("title", "Title must have a value.").not().isEmpty();
check("content", "Content must have a value.").not().isEmpty();


var title = req.body.title;
var slug = req.body.slug.replace(/\#+/g, "-").toLowerCase();
if (slug == "") {
    slug = title.replace(/\#+/g, "-").toLowerCase();
}

var content = req.body.content;
var errors = validationResult(req);
if (errors){
    console.error(errors);
    
    
    res.render("admin/add_page",{
        errors: errors,
        title:title,
        slug:slug,
        content:content
    });
} else {
   Page.findOne({slug:slug}, function(err, page){
       if (page) {
           req.flash("danger","Page slug exists, choose another.");
           res.render("admin/add_page",{
            
            title:title,
            slug:slug,
            content:content
        });
       } else {
           var Page = new Page({
               title:title,
               slug:slug,
               content:content,
               sorting:0
           });
           Page.save(function(err){
               if (err) {
                   return console.log(err);
                   
               } else {
                   req.flash("Success", "Page added!");
                   res.redirect("/admin/pages");
               }
           })
       }
   })
    
}

});



//Exports
module.exports = router;

But my result in console is

Result { formatter: [Function: formatter], errors: [] }

Upvotes: 1

Views: 2226

Answers (3)

Yves Kipondo
Yves Kipondo

Reputation: 5603

You can pass in your router definition an array of every validation which you want to perform on each request which is handle by a given route.

like this

router.post(route_path, [...], function(req, res) {});

For your specific case It will look like this

const { check, validationResult } = require('express-validator');

const router = express.Router();

router.post('/add-page', [
    check("title", "Title must have a value.").not().isEmpty(),
    check("content", "Content must have a value.").not().isEmpty()
], function(req, res) {
    const errors = validationResult(req);
    if(!errors.isEmpty()) {
        console.log(errors);


        return res.status(500).json({
            errors
        });

        /*
        return res.render("admin/add_page",{
            errors: errors,
            title:title,
            slug:slug,
            content:content
        });
        */
    }

    // And the other code goes when validation succeed 
}

Upvotes: 0

Arun
Arun

Reputation: 653

express is a middleware framework express-validator is used to validate the request for that we need to call the validator before the request is actually passed for that we use express validator before the callback method you have to check for the validation for that you will pass a middleware before the callback

here how you suppose to do that

router.post(
  "/add-page",
  [
    check("title", "Title must have a value.").not().isEmpty(),
    check("content", "Content must have a value.").not().isEmpty(),
  ],
   (req, res) => {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        console.log(errors);//if client get any error the code will pass here you can do anything according to your choice
        });

      } catch (err) {
      console.log(err);
    }
  }
);

Upvotes: 0

Afaq Ahmed Khan
Afaq Ahmed Khan

Reputation: 2302

What you should be logging is

if (!errors.isEmpty()) {
   console.log(res.status(422).json({ errors: errors.array() }));
 }

This is the correct way of logging errors in express validator docs. Whenever a request that includes invalid fields is submitted, your server will respond like this:

{
 "errors": [{
   ... //fields
  }]
}

For all the available validators in express-validator (just like its options), take a look at validator.js docs here.

Upvotes: 2

Related Questions