Nodejs - Joi Check if string is in a given list

后端 未结 2 1922
粉色の甜心
粉色の甜心 2021-02-18 15:22

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

相关标签:
2条回答
  • 2021-02-18 15:35

    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

    0 讨论(0)
  • 2021-02-18 15:40

    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 (-:

    0 讨论(0)
提交回复
热议问题