javascript - 如何使用 Joi 最新版本验证枚举字符串?

标签 javascript node.js typescript express

如何验证枚举字符串?

我过去常常按照这里的建议去做:https://github.com/hapijs/joi/issues/1449

enum UserRole {
  Admin = 'admin',
  Staff = 'staff'
}

const validator = {
  create: Joi.object().keys({
    first_name: Joi.string().min(1),
    last_name: Joi.string()
      .min(1)
      .required(),
    password: Joi.string()
      .regex(/^[\x20-\x7E]+$/)
      .min(8)
      .max(72)
      .required(),
    role: Joi.string()
      .valid([UserRole.Admin, UserRole.Staff])
      .optional(),
    is_active: Joi.boolean().optional()
  })
};

但是现在,错误:方法不再接受数组参数:有效

最佳答案

我可以像这样使用 Joi.any().valid() 让它工作,希望对你有用。

const Joi = require("@hapi/joi");

const roles = ["admin", "staff"];

const schema = Joi.object({
  first_name: Joi.string().min(1),
  last_name: Joi.string()
    .min(1)
    .required(),
  password: Joi.string()
    .regex(/^[\x20-\x7E]+$/)
    .min(8)
    .max(72)
    .required(),
  role: Joi.any().valid(...roles),
  is_active: Joi.boolean().optional()
});

例子:

当使用有效 Angular 色时没有错误。

const { error, value } = schema.validate({
  first_name: "Magnus",
  last_name: "Carlsen",
  password: "chess/1234",
  role: "staff"
});

console.log(error); //undefined

当没有使用 Angular 色时没有错误。

const { error, value } = schema.validate({
  first_name: "Magnus",
  last_name: "Carlsen",
  password: "chess/1234"
});

console.log(error); //undefined

当使用不同的 Angular 色时,会出现验证错误。

const { error, value } = schema.validate({
  first_name: "Magnus",
  last_name: "Carlsen",
  password: "chess/1234",
  role: "unknown"
});

console.log(error); // Error [ValidationError]: "role" must be one of [admin, staff]...

关于javascript - 如何使用 Joi 最新版本验证枚举字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58486977/

相关文章:

javascript - Angular md-fab-toolbar 跟随滚动

javascript - computeArea() 在 google map api v3 中返回 [object object]

javascript - jquery width() 方法总是更新初始宽度

node.js - 在 stdin 中写入生成的 child_process 不起作用

node.js - 如何使用 process.hrtime.bigint

javascript - Pug - 包含带有嵌入式 HTML 的 Markdown 文件

angularjs - 如何在弹性beanstalk上安装ng

javascript - NodeJS Redis - 在后台重新连接

typescript - 使用 jest 模拟 AWS.DynamoDB.DocumentClient 的构造函数

javascript - 将多个 Typescript 文件编译为一个 javascript 文件