1

I am new to Joi. I try to put some rules to signup users. But every new user could signup and "if" command is always executed.

const Joi = require ('joi')

const authSchema = Joi.object().keys({
email:Joi.string().email().required(),
password:Joi.string().min(10).max(24).required()
})

exports.email = (req,res,next) => { 
if(authSchema.validate(req.body)){
    console.log("je suis dans le middleware joi")
    console.log("-------> req.body")
    console.log(req.body)
    // authSchema.validate({email: req.body.email, password: req.body.password})
    // authSchema.validate(req.body)

    next()
} else{
    res.status(400).json({ error: "erreur de data validataion" });
    console.log("erreur ne convient pas a joi")
}

}

1 Answer 1

3

Hey use this is how i do main

validateInput(rowData) {
    const schema = Joi.object().keys({
      email: Joi.string().email().required(),
      firstName: Joi.string().required(),
      lastName: Joi.string().required(),
      contact: Joi.string().required(),
      roleId: Joi.number().allow("", null),
    });
    return schema.validate(rowData);
  },

And call it like this

    const { error } = await validateInput(user); // request body user.
        if (error) {
          return res.status(400).send({ message: error.details[0].message });
// it will return for you the message.
        }

Here is a link on how you can use Joi as a middleware. https://dev.to/tayfunakgc/middleware-based-joi-validation-in-expressjs-2po5

Sign up to request clarification or add additional context in comments.

3 Comments

Could you give me an example for middleware.
I have not seen people use joi in middleware form may be try express-validator
Added a link for the use of the middleware please this answer helps. accept it for future use

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.