Search code examples
javascriptjoi

Joi conditional .required()


I have a function that returns a Joi schema. The string in that schema can either be required or optional.

Here is my function:

function myString(required) {
  const schema = Joi.string();

  if (required) schema.required();

  return schema;
}

Calling myString(true) does not apply .required(). However, the string is required if my function is defined as:

function myString() {
  const schema = Joi.string().required();

  return schema;
}

I wanted a function to apply that conditional .required() (and other validations) so I don't waste time writing Joi.string() or Joi.string().required() everywhere. So, the following doesn't fit my need:

function myString(required) {
  return required ? Joi.string().required() : Joi.string();
}

Why is my first function not working? How can I make it work?


Solution

  • joi function return this instance you need to store that to variable. it's builder

    function myString(required) {
      let schema = Joi.string();
    
      if (required) {
        schema = schema.required();
      }
    
      return schema;
    }