Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

217
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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;
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!