Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 541
Sandy Garrido Avatar asked Jan 23 '26 04:01

Sandy Garrido


2 Answers

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.

like image 162
Yilmaz Avatar answered Jan 25 '26 17:01

Yilmaz


Joi or means that one or more of either-this-field and or-this-field should appear in the object. Appear is different than validate here.
You can omit one of the properties, but whenever you provide a value it has to match the validation rule.

It makes sense: when someone provides a bad value, you probably want to throw an error instead of swallowing the bad data silently even if it's optional.

like image 26
Jean-Baptiste Martin Avatar answered Jan 25 '26 17:01

Jean-Baptiste Martin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!