Home > database >  How to use Joi alternatives conditional for schema validation?
How to use Joi alternatives conditional for schema validation?

Time:10-12

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

CodePudding user response:

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() })
 })
  • Related