hapijs / joi

The most powerful data validation library for JS
Other
20.95k stars 1.51k forks source link

I can't validate with the Joi class. #2994

Closed bravono closed 1 year ago

bravono commented 1 year ago

Support plan

Context

What are you trying to achieve or the steps to reproduce?

const some = 'properly formatted code example';

const Joi = require("joi");

const courses = [
  { id: 1, name: "course1" },
  { id: 2, name: "course2" },
  { id: 3, name: "course3" },
];

app.post("/api/courses", (req, res) => {
  const schema = {
    name: Joi.string().min(3).required(),
  };

  const result = Joi.validate(req.body, schema);

  if (error) {
    res.status(400).send(result);
    return;
  }

  const course = { id: courses.length + 1, name: req.body.name };

  courses.push(course);

  res.send(course);
});

What was the result you got?

TypeError: Joi.validate is not a function at C:\Users\Ahbideen\express-demo\index.js:34:22 at Layer.handle [as handle_request] (C:\Users\Ahbideen\express-demo\node_modules\express\lib\router\layer.js:95:5) at next (C:\Users\Ahbideen\express-demo\node_modules\express\lib\router\route.js:144:13) at Route.dispatch (C:\Users\Ahbideen\express-demo\node_modules\express\lib\router\route.js:114:3) at Layer.handle [as handle_request] (C:\Users\Ahbideen\express-demo\node_modules\express\lib\router\layer.js:95:5) at C:\Users\Ahbideen\express-demo\node_modules\express\lib\router\index.js:284:15 at Function.process_params (C:\Users\Ahbideen\express-demo\node_modules\express\lib\router\index.js:346:12) at next (C:\Users\Ahbideen\express-demo\node_modules\express\lib\router\index.js:280:10) at C:\Users\Ahbideen\express-demo\node_modules\body-parser\lib\read.js:137:5 at AsyncResource.runInAsyncScope (node:async_hooks:206:9)

What result did you expect?

{ "error": { "isJoi": true, "name": "ValidationError", "details": [ { "message": "\"name\" is required", "path": [ "name" ], "type": "any.required", "context": { "key": "name", "label": "name" } } ], "_object": {} }, "value": {} }

Nargonath commented 1 year ago

You have this error because the validate function is not available from the global module you require but from a Joi schema. Try this instead:

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

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

See it live here: https://runkit.com/nargonath/joi-validate-usage

Another thing also, you should not declare your schema inside the endpoint because it's going to be compiled again each time your endpoint is executed which can have an impact on your application performance. You should declare it outside in the global scope of your NodeJS module.

Nargonath commented 1 year ago

From what I can see, this issue stems from an improper use of the library so I'm going to close this. Let me know if you still have trouble even with the solution I suggested above.