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

247
Views
How to use Joi alternatives conditional for schema validation?

I have a use case where a schema field is mandatory depending on the value of another field,
eg. If the schema has 2 fields, name and addr,
if the value of name field is "test" only then addr field is required.

I am using Joi for object validation,
Following is my sample code -

const Joi = require('joi');


let test = async() => {
    const schema = Joi.object({
        name: Joi.string().required(),
        addr: Joi.alternatives().conditional('name', {is: 'test', then: Joi.string().required()})
    });

    const request = {
        name: "test"
    }

    // schema options
    const options = {
        abortEarly: false, // include all errors
        allowUnknown: true, // ignore unknown props
        stripUnknown: true // remove unknown props
    };

    // validate request body against schema
    const validationResponse = await schema.validate(request, options);
    console.log("validationResponse => ", validationResponse);

    return true;
};

test();

current output - validationResponse => { value: { name: 'test' } }

what I'm expecting is validationResponse to have error message that addr field is missing.

I tried to refer -
https://www.npmjs.com/package/joi
https://joi.dev/api/?v=17.4.2#alternativesconditionalcondition-options

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

0

Do you really need Joi.alternatives? Why don't you use Joi.when instead?

 Joi.object({
   name: Joi.string().required(),
   addr: Joi.string().when('name', { is: 'test', then: Joi.required() })
 })
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!