Node.js validateReturn function: Joi.objectId not a function

My current validateReturn function:

function validateReturn(req) {

const schema = {

customerId: Joi.objectId().required(),

movieId: Joi.objectId().required(),

};

return Joi.validate(req, schema);

}

All my tests now fail because of :

error: Joi.objectId is not a function TypeError: Joi.objectId is not a function

The other cases in the project where I am using .objectId are still working. I know that objectId is a separate npm package and that’s why we add it in the validation.js in the startup but I can’t seem to work out why it isn’t working inside of the rentals.js file.

I have the same problem, did you manage to solve it?

@Mathew, below is my code which is working fine.

const Joi = require(“joi”);
Joi.objectId = require(“joi-objectid”)(Joi);

function validateRental(rental) {
const schema = Joi.object({
customerId: Joi.objectId(),
movieId: Joi.objectId,
});
return schema.validate(rental);
}

There is a small change in Joi syntax which Mosh taught and what is currently there in Joi documentaion.
I have used the latest syntax, refer Joi documentation, ref: joi.dev - 17.5.0 API Reference

the above code will not work if you use .required() next to Joi.objectId.
without using required the code works fine, and it looks like in this case required in inbuilt in Joi-objectid.

Try removing .required() and change the Joi syntax, this should work for you.

2 Likes

I had to add this line back in at the top of returns.js

Joi.objectId = require(‘joi-objectid’)(Joi);

It’s part of the validate startup code, not sure why all the other routes work and not returns.js

1 Like

Your method works bro!
Thanks :slight_smile:

I think something changed in the last 2 years here is a currently working solution
function validateReturn(req) {
const schema = Joi.object ({
customerId: Joi.string().hex().length(24),
movieId: Joi.string().hex().length(24)

});
return schema.validate(req);

}