Joi validation when either latitude or longitude or address

100 Views Asked by At

In my request, I have address in which i have latitude, longitude, address line, city and postal code

"Address": {
  "Id": "",
  "AddressLine": "lll",
  "City": "nbn",
  "PostalCode": "201321",
  "County": "",
  "Longitude": "",
  "Latitude": ""
}

Condition is that i have to validate latitude and longitude OR addressline city and postalcode.

If lat/long null or empty then we need to validate addressline city and postalcode. So either lat/long or adress field should be there.

I tried below code

const Joi = require("joi");
const dataSchema = Joi.object({
  Id: Joi.string().required().label("Task ID"),
  Address: Joi.object({
    Longitude: Joi.number().when(
      Joi.object({ AddressLine: Joi.forbidden(), City: Joi.forbidden(), PostalCode: Joi.forbidden() }).or('AddressLine', 'City', 'PostalCode'),
      { then: Joi.forbidden() }
    ).label("Longitude"),
    Latitude: Joi.number().when(
      Joi.object({ AddressLine: Joi.forbidden(), City: Joi.forbidden(), PostalCode: Joi.forbidden() }).or('AddressLine', 'City', 'PostalCode'),
      { then: Joi.forbidden() }
    ).label("Latitude"),
    AddressLine: Joi.string().label("AddressLine"),
    City: Joi.string().label("City"),
    PostalCode: Joi.string().label("PostalCode"),
  })
  .unknown(true),
}).unknown(true);

function validateData(data) {
  return dataSchema.validate(data);
}

module.exports = {
  validateData,
};

1

There are 1 best solutions below

0
Kamran On

If latitude and longitude have priority over addressline, city and postalcode, the below should work

Joi.object({
  Address: Joi.object({
    Longitude: Joi.number().allow(null),
    Latitude: Joi.number().allow(null),
    AddressLine: Joi.string().when('Longitude', { 
        is: null,
        then: Joi.string().required(),
        otherwise: Joi.string().when('Latitude', { 
            is: null, 
            then: Joi.string().required(),
            otherwise: Joi.string().optional().allow(null, "")
        }),
    }),
    City:  Joi.string().when('Longitude', { 
        is: null, 
        then: Joi.string().required(),
        otherwise: Joi.string().when('Latitude', { 
            is: null, 
            then: Joi.string().required(),
            otherwise: Joi.string().optional().allow(null, "")
        }),
    }),
    PostalCode:  Joi.string().when('Longitude', { 
        is: null, 
        then: Joi.string().required(),
        otherwise: Joi.string().when('Latitude', { 
            is: null, 
            then: Joi.string().required(),
            otherwise: Joi.string().optional().allow(null, "")
        }),
    }),
   }).unknown(true),
}).unknown(true)