简体   繁体   中英

Make all fields or some of required by passing options to schema

I am using Joi for validating body data.

So, If I have an API which creates vehicles. I would create an schema like below.

const validateUserVehicleData = (data) => {
  const schema = Joi.object({
    id: Joi.string(),
    odometer_count: Joi.number().allow(null),
    registration_number: Joi.string(),
    current_milage: Joi.number(),
    last_service_date: Joi.date(),
    last_service_km: Joi.number(),
    chassis_num: Joi.string(),
    engine_num: Joi.string(),
    vehicle_id: Joi.string(),
  });
  return schema.validate(data);
};

I know I can do here vehicle_id: Joi.string().required() to make them individually required.

But I want make some fields to be required by passing dynamically data to schema object.

Like, If I want to make only few of them required like below.

//It should make registration_number and currrent_mileage required
const schema = Joi.object({..}).required(['registration_number', 'currrent_mileage ']); // I know this doesn't exist but if there is any workaround

I also tried something like below to make all of them required, but it is not working neither throwing any error.

// It should make all fields required
const schema = Joi.object({..}).required(); 

One thing I can do here creating multiple schema for same data, which is working fine.

But ended up creating three to four schema for validating same data.

Is there any work around here? I went through doc, but I couldn't find any thing like these.

Update

For validating all fields, I found a work around.

Joi.object({
    registration_number: Joi.string(),
    vehicle_id: Joi.string(),
    .....
}).options({presence: 'required'})

To pick required keys, use and method

According to the docs of object.and(...peers, [options]) :

Defines an all-or-nothing relationship between keys where if one of the peers is present, all of them are required as well where:

  • peers - the string key names of which if one present, all are required. options
  • optional settings :
    • separator - overrides the default. hierarchy separator. Set to false to treat the key as a literal value.
const schema = Joi.object({ ... }).and("registration_number", "current_mileage");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM