4
votes

I have this joi schema using .number() for a body parameter 'public'

contactSchema: Joi.object().keys({
    email: Joi.string().email().required(),
    public: Joi.number().required()
}),

If I allow the paremeter to be 0 in some instance ...

if(req.session.sessionEmail){
    var isPublic = 0;
  } else {
    var isPublic = 1;
  }

... joi says its invalid.

If I don't pass a 0 ... all is good?

if(req.session.sessionEmail){
    var isPublic = 2;
  } else {
    var isPublic = 1;
  }

Why does it fail in case of 0?

https://github.com/hapijs/joi/blob/master/API.md#number---inherits-from-any

2
Never used Joi before, but based on the coerciveness of 0 in JS, it might be getting mixed up and seeing this as "falsey". From the docs there's a min function, would Joi.number().min(0) maybe work? Although, unless I am misunderstanding what isPublic represents....wouldn't boolean() be more appropriate? - James

2 Answers

5
votes

Try this one: Joi.number().integer()

contactSchema: Joi.object().keys({
    email: Joi.string().email().required(),
    public: Joi.number().integer().required()
}),
0
votes

Please try with

userId: joi.number().integer().min(1).required()