TypeError: Joi.validate is not a function

4k views Asked by At

I have tried all the solutions offered in this site and GitHub but it didn't work for me because my routes/user.js is structured differently. Also, I am new in Nodejs. I need help to change const result = Joi.validate(req.body, schema); in the routeHelper.js and

const {validateBody, schemas} = require('../helpers/routehelpers');  
router.route('/signup')
.post(validateBody(schemas.authSchema),userController.signup);

in the routes/user.js

 //routeHelper.js
 const Joi = require('joi');
    module.exports = {
      validateBody: (schema) => {
        return (req, res, next) => {
          const result = Joi.validate(req.body, schema);
          if (result.error) {
            return res.status(400).json(result.error);
          }

      if (!req.value) { req.value = {}; }
      req.value['body'] = result.value;
      next();
    }
  },

  schemas: {
    authSchema: Joi.object().keys({
      email: Joi.string().email().required(),
      password: Joi.string().required()
    })
  }
}

//routes/user.js
const express = require('express'),
      router  = require('express-promise-router')();
const userController = require('../controller/user');
const {validateBody, schemas} = require('../helpers/routehelpers');
const passport = require('passport')
const passportConfig = require('../passport')

router.route('/signup')
.post(validateBody(schemas.authSchema),userController.signup);



router.route('/signin')
.post(userController.signin);

router.route('/secret')
.get(passport.authenticate('jwt',{session:false}),userController.secret);

module.exports = router;
2

There are 2 answers

0
Jess Nguyen On

const result = schema.validate(req.body); It's mentioned here -> https://github.com/sideway/joi/issues/2145#issuecomment-568173652

0
Sadaf Shafi On

the answer is that the schema you've has to be a JOI object and you'd have to use it likewise here's the sample code

const schema = Joi.object({
    name: Joi.string().min(6).required(),
    email : Joi.string().min(6).required().email(),
    password: Joi.string().min(6).required()
});

const vall =  schema.validate(req.body);