How to use enum values with Joi String validation

2020-06-10 02:23发布

I am using Joi validator for my HTTP requests. There I have a parameter called type. I need to make sure that the possible values for the parameter are either "ios" or "android".

How can I do that?

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

2条回答
2楼-- · 2020-06-10 02:49

Maybe it will be useful for anyone who wants to check values based on existing enum/array of values.

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

Then just use this:

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

const myObj = { type: 'none' };
const result = Joi.validate(myObj, schema);
查看更多
ゆ 、 Hurt°
3楼-- · 2020-06-10 02:55

You can use 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);

This gives an error ValidationError: child "type" fails because ["type" must be one of [ios, android]]

查看更多
登录 后发表回答