如何在 Joi 字符串验证中使用枚举值

How to use enum values with Joi String validation

我正在为我的 HTTP 请求使用 Joi 验证器。我有一个名为 type 的参数。我需要确保参数的可能值是 "ios" 或 "android".

我该怎么做?

body : {
  device_key : joi.string().required(),
  type : joi.string().required()
}

您可以使用 valid.

const schema = Joi.object().keys({
  type: Joi.string().valid('ios', 'android'),
});

const myObj = { type: 'none' };
const result = Joi.validate(myObj, schema);
console.log(result);

这会报错ValidationError: child "type" fails because ["type" must be one of [ios, android]]

也许它对任何想要根据现有 enum/array 值检查值的人都有用。

const SomeEnumType = { TypeA: 'A', TypeB: 'B' };

那么就用这个:

const schema = Joi.object().keys({
  type: Joi.string().valid(...Object.values(SomeEnumType)),
});

const myObj = { type: 'none' };
const result = Joi.validate(myObj, schema);

我迟到了这个答案。 但以下内容对其他人有帮助,他们希望将枚举值与 Joi 字符串验证一起使用:

function validateBody(bodyPayload) {
    const schema = Joi.object({
        device_key : Joi.string().required(),
        type : Joi.string().valid('ios','android'),

    });
    return schema.validate(admin);
}

const bodyPayload = {device_key:"abc", type: "web"};
const result = validateBody(bodyPayload);

reference : https://hapi.dev/module/joi/api/#anyallowvalues

对于打字稿用户,

getEnumValues<T extends string | number>(e: any): T[] {
        return typeof e === 'object' ? Object.keys(e).map(key => e[key]) : [];
}

Joi.string().valid(...getEnumValues(YOUR_ENUM));
function getEnumValues<T extends string | number>(e: any): T[] {
    return typeof e === 'object' ? Object.values(e) : [];
}

Joi.string().valid(...getEnumValues(YOUR_ENUM));