I have a schema like this (the real one is doble the size):
const optionalIfPatch = { patch: (schema: AnySchema) => schema.optional() };
const personValidator = Joi.object({
username: Joi.string().token().lowercase().min(5).required().alter(optionalIfPatch),
password: Joi.string().min(6).required().alter(optionalIfPatch),
fullName: Joi.string().min(5).required().alter(optionalIfPatch),
email: Joi.string().email().required().alter(optionalIfPatch),
userProfile: Joi.string().valid(...Object.keys(UserProfile)).default(UserProfile.default),
address: Joi.object({
streetAddress: Joi.string().min(5),
city: Joi.string().min(3),
state: Joi.string().min(3),
zipCode: Joi.string().min(3),
}),
}).options({ abortEarly: false });
Basically I want make required fields optional with the personValidator.tailor() function at validation time. It works this way, but I was trying to make this behavior into an extension:
const joiExtensions: Joi.ExtensionFactory[] = [
(joi: Joi.Root) => ({
type: /.*/,
rules: {
requiredButPatchable: {
alias: 'reqOrPatch',
method() {
return this.required().alter(optionalIfPatch); // GOT STUCK HERE
}
},
},
}),
];
To be used like this:
Joi.string().token().lowercase().min(5).requiredButPatchable()
But to be honest, I’ve been researching for three days and couldn’t find a proper explanation of how to build an extension like this (using Joi itself).
(Also, when I extend the Joi model, I loose the autocompletion for VSCode… is there a way arround it?)
I’ve tried the Joi docs, git issues, stack overflow questions… couldn’t find a proper answer.
I want to use the alter()and tailor() functionalities as an extension so I can reduce the repeated code…



