Admin will create users, and while doing so he will enter some random string as a password. When admin edit the existing user, he don't need to enter any password unless he wants to change it. If the admin doesn't enter any password, then the old password will be used.
So i am trying to use .when() to handle this case. When _id exists in the payload (which is possible only when the user exists), then we should make the password field optional or else password is required.
Here is my Joi validation
const usersJoiSchema = Joi.object({
_id: Joi.string().optional(),
firstName: Joi.string().required(),
lastName: Joi.string().required(),
email: Joi.string().required(),
password: Joi.string().when('_id', { is: Joi.exist(), then: Joi.optional(), otherwise: Joi.required() })
})
Joi have a method .when in case of such cases. But for some strange reason it is giving me
{"statusCode":500,"error":"Internal Server Error","message":"An internal server error occurred"}
as the response of the api, and there is nothing in the server console.
I tried to compare the string length for _id as well instead of exists() and i have also tried
password: Joi.string().when('_id', { is: Joi.string().required(), then: Joi.string().optional(), otherwise: Joi.string().required() }),
password: Joi.string().when('_id', { is: Joi.string(), then: Joi.string().optional(), otherwise: Joi.string().required() }),
for password key, but still the same issue.
If any one has any kind of idea on this issue, please help me.