Nodejs - Joi Check if string is in a given list

有些话、适合烂在心里 提交于 2020-05-12 11:15:58

问题


I'm using Joi package for server side Validation.
I want to check if a given string is in a given list or if it is not in a given list.(define black list or white list for values)
sth like an "in" or "notIn" function.how can I do that?

var schema = Joi.object().keys({
    firstname: Joi.string().in(['a','b']),
    lastname : Joi.string().notIn(['c','d']),
});

回答1:


How about:

var schema = Joi.object().keys({
    firstname: Joi.string().valid(['a','b']),
    lastname : Joi.string().invalid(['c','d']),
});

There are also aliases: .allow and .only

and .disallow and .not




回答2:


You are looking for the valid and invalid functions.
v16: https://hapi.dev/module/joi/api/?v=16.1.8#anyvalidvalues---aliases-equal
v17: https://hapi.dev/module/joi/api/?v=17.1.1#anyvalidvalues---aliases-equal

As of Joi v16 valid and invalid no longer accepts arrays, they take a variable number of arguments.

Your code becomes

var schema = Joi.object().keys({
    firstname: Joi.string().valid(...['a','b']),
    lastname: Joi.string().invalid(...['c','d']),
});

Can also just pass in as .valid('a', 'b') if not getting the values from an array (-:



来源:https://stackoverflow.com/questions/41408469/nodejs-joi-check-if-string-is-in-a-given-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!