I want to send joi validation error in response how can I do this
here is my code but it is not working,
File mainfile.js
const { loginSchema } = require("./helper/validate_schema.js"); var loginUser = async (req, res, next) => { const { email, password } = req.body; try { let result = await loginSchema.validateAsync(req.body); console.log(result) res.json({Error:result}) } catch (error) { next(error); } };
File validate_schema.js
const joi = require('joi'); const loginSchema = joi.object({ email:joi.string().email().required(), password:joi.string().min(5).required() }) module.exports={loginSchema}
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You write a validate function using schema:
function validate(req) { const schema = Joi.object().keys({ email: joi.string().email().required(), password: joi.string().min(5).required(), }); return Joi.validate(req, schema); }
then inside post route:
router.post("/", async (req, res) => { const { error } = validate(req.body); // check the error object first console.log(error) if (error) return res.status(400).send(error.details[0].message); // if not error write your logic });
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0