How to send joi validation error in API response

Viewed 458

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}
1 Answers

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
});
Related