Skip to content
Advertisement

Joi validate at least one of 2 input fields are completed

I seem to hit a roadblock when it comes to joi’s .or() function as it doesn’t seem to implement as I’d expect.

I have 2 text input fields, both have their own way of validating, though only at least one is required.

    const schema = joi
      .object({
        "either-this-field": joi.string().trim().max(26),
        "or-this-field": joi
          .string()
          .trim()
          .regex(/^d+$/)
          .max(26)
        "other-field-1": joi.string().required(),
        "other-field-2": joi.string().max(40).required(),
    
      })
      .or("either-this-field", "or-this-field");

it just seems that this or doesn’t do as I’d expect and each field from the or is just validated as per it’s own validation rules

if neither field has values, then I’ll display error for both fields until at least one is completed

Advertisement

Answer

From here

var schema = Joi.alternatives().try(
  Joi.object().keys({
    a: Joi.string().allow(''),
    b: Joi.string()
    }),
  Joi.object().keys({
    a: Joi.string(),
    b: Joi.string().allow('')
    })
);

alternatives().try() adds an alternative schema type for attempting to match against the validated value. You are passing two options and it will choose one of them.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement