I am a beginner and currently working my way through a node.js API authentication tutorial. All going well until having to refactor code into separate files and now I keep getting the following error "TypeError: schema.validate is not a function" when sending a JSON request via Postman, regardless if the request should fail the validation or not.
Here is my code for validation.js
//Validation
const Joi = require('@hapi/joi');
//Register Validation - wrap it in a function as there will be multiple schemas
const registerValidation = data => {
const schema = {
name: Joi.string().min(6).required(),
email: Joi.string().min(6).required().email(),
password: Joi.string().min(6).required()
}
return Joi.assert(data, schema);
}
// Login Validation
const loginValidation = data => {
const schema = {
email: Joi.string().min(6).required().email(),
password: Joi.string().min(6).required()
}
return Joi.assert(data, schema);
}
module.exports.registerValidation = registerValidation;
module.exports.loginValidation = loginValidation;
My auth.js code is like so
const router = require('express').Router();
const User = require('../model/User');
const { registerValidation } = require('../validation');
router.post('/register', async (req, res) => {
//Validate data before creating user
// const { error } = schema.validate(req.body);
const { error } = registerValidation(req.body);
if(error) return res.status(400).send(error.details[0].message);
const user = new User({
name: req.body.name,
email: req.body.email,
password: req.body.password,
date: req.body.date
});
try {
const savedUser = await user.save();
res.send(savedUser);
}catch(err){
res.status(400).send(err);
}
});
router.post('/login')
module.exports = router;
Can someone assist at all? The only thing I have changed is that I was using Joi.validate which is no longer valid according to the docs so I have updated it to Joi.assert.
Many thanks
Use the below approach for validation as joi.validate is no longer supported
const schema = Joi.object({
name: Joi.string().min(6).required(),
email: Joi.string().min(6).required().email(),
password: Joi.string().min(6).required()
})
return schema.validate(data)