schema validation fails although parameter is available schema validation fails although parameter is available express express

schema validation fails although parameter is available


Actually Joi has access to the userId and can properly validate it or not, here's why:

// replace thisconst { error } = joi.validate(req, schema);// by thisconsole.log(req.params.userId);const { error } = joi.validate(req, schema);console.log(error.toString());

console output while visiting localhost:3000/users/10:

10ValidationError: child "params" fails because [child "userId" fails because ["userId" must be a valid GUID]]

and while visiting an URL including a valid GUID in the params, like ``:

ad3756ae-2661-4d8c-aeda-dd51deef5ea9ValidationError: "_readableState" is not allowed. "readable" is not allowed. "_events" is not allowed. "_eventsCount" is not allowed. "_maxListeners" is not allowed. "socket" is not allowed. "connection" is not allowed. "httpVersionMajor" is not allowed. "httpVersionMinor" is not allowed. "httpVersion" is not allowed. "complete" is not allowed. "headers" is not allowed. "rawHeaders" is not allowed. "trailers" is not allowed. "rawTrailers" is not allowed. "aborted" is not allowed. "upgrade" is not allowed. "url" is not allowed. "method" is not allowed. "statusCode" is not allowed. "statusMessage" is not allowed. "client" is not allowed. "_consuming" is not allowed. "_dumped" is not allowed. "next" is not allowed. "baseUrl" is not allowed. "originalUrl" is not allowed. "_parsedUrl" is not allowed. "query" is not allowed. "res" is not allowed. "route" is not allowed

So Joi has access to everything that it needs and works as expected. 🚀


So why the error 400?

Well, as logged in the console, Joi fails the validation for req. That is because, by default, Joi doesn't accept unknown params in an object. You can change this with .unknown(true) which validates an object even if unknown parameters are included.

So, in your case, you should replace the code of policies/users.js by the following:

const joi = require('joi');const schemaValidation = require('../middleware/schemaValidation.js');module.exports = {    getUserById: (req, res, next) => {        // properly defines a schema with optional parameters        const schema = joi.object({            params: joi.object({                userId: joi.string().guid().required()            }).unknown(true),        }).unknown(true);        schemaValidation(schema, req, res, next);    }}

Now, when you visit again an URL including a valid GUID (like http://localhost:3000/users/ad3756ae-2661-4d8c-aeda-dd51deef5ea9), everything happens as expected and ""everything is fine" is being sent by the server! 🎉