简体   繁体   English

通过将选项传递给架构来使所有字段或某些字段成为必填字段

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

I am using Joi for validating body data.我正在使用Joi来验证身体数据。

So, If I have an API which creates vehicles.所以,如果我有一个创建车辆的 API。 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.我知道我可以在这里做vehicle_id: Joi.string().required()使它们单独成为必需的。

But I want make some fields to be required by passing dynamically data to schema object.但是我想通过将动态数据传递给模式 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选择所需的键,使用and方法

According to the docs of object.and(...peers, [options]) :根据object.and 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. peers - 字符串键名称,如果存在,则所有键名都是必需的。 options选项
  • optional settings : optional settings
    • separator - overrides the default. separator - 覆盖默认值。 hierarchy separator.层次分隔符。 Set to false to treat the key as a literal value.设置为 false 将键视为文字值。
const schema = Joi.object({ ... }).and("registration_number", "current_mileage");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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