Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joi validation when either of two values are present or missing

Have three parameters: latitude, longitude, zipcode

I need a joi validation that

  • requires latitude AND longitude when either is present OR zipcode is missing
  • requires zipcode when EITHER latitude or longitude is missing.

Something like this?

Joi.object().keys({
    latitude: Joi.number().when('zipcode', { is: undefined, then: Joi.required() }),
    longitude: Joi.number().when('zipcode', { is: undefined, then: Joi.required() }),
    zipcode: Joi.number().when(['latitude', 'longitude'], { is: undefined, then: Joi.required() })
});

I'm thinking there is a more elegant solution maybe using object.and()

like image 314
Scott Avatar asked Oct 27 '16 22:10

Scott


2 Answers

You can validate multiple conditions in the following schema.

    const schema = Joi.object().keys({
        searchby: Joi.string().valid('phone', '_id', 'cno').required(), // field name
        searchvalue: Joi
            .when('searchby', { is: "phone", then: Joi.string().regex(/^(923)\d{9}$/, 'numbers').max(12).min(12).required() })
            .when('searchby', { is: "_id", then: Joi.objectId().required() })
            .when('searchby', { is: "nic", then: Joi.number().required() })
    });
like image 156
Mohammad Khalid Avatar answered Sep 29 '22 11:09

Mohammad Khalid


This solution may be useful:

schema = Joi.object().keys({
  location: Joi.object().keys({
    lat: Joi.number(),
    long: Joi.number()
  }).and('lat', 'long'),
  timezone: Joi.alternatives()
    .when('location', {
        is: null,
        then: Joi.number().required(),
        otherwise: Joi.number()
    })
});
like image 35
Heartbit Avatar answered Sep 29 '22 11:09

Heartbit