Joi: Joi does not return an error if the value being validated is `undefined`

Created on 13 Nov 2017  路  11Comments  路  Source: sideway/joi

Context

  • node version: 8.9.1
  • joi version: 13.0.2
  • environment (node, browser): node
  • used with (hapi, standalone, ...): standalone
  • any other relevant information: n.a.

What are you trying to achieve or the steps to reproduce ?

Describe your issue here, include schemas and inputs you are validating if needed.

const schema = {
    a: Joi.number().required
};

let value_undefined;
const result_undefined_value = Joi.validate(value_undefined, schema);
console.log(result_undefined_value); 

Which result you had ?

{ error: null,
  value: undefined,
  then: [Function: then],
  catch: [Function: catch] }

Result available online: https://travis-ci.org/nelsonic/joi-browser-test/builds/301663402#L550-L559

What did you expect ?

I would expect joi to show an error if the value being validated is undefined
But it says error is null ...
I could not find this documented anywhere in the API https://github.com/hapijs/joi/blob/v13.0.2/API.md
Is this _desirable_?

non issue support

Most helpful comment

Ah, so

    const schema = Joi.object({
        x: Joi.required()
    }).required()
    console.log(Joi.validate(undefined, schema))

would work. Thank you!

All 11 comments

Object schemas are not created as required, that's totally expected. See conversion rules in https://github.com/hapijs/joi/blob/master/lib/cast.js if documentation is not clear enough.

For the record that kind of conversion is documented on https://github.com/hapijs/joi/blob/master/API.md#compileschema.

thanks for clarifying @Marsup 馃憤

@Marsup But explicit schema creation is also leading to the same behavior:

const schema = Joi.object({
  x: Joi.required()
})
console.log(Joi.validate(undefined, schema))

would log

{ 
  error: null,
  value: undefined,
  then: [Function: then],
  catch: [Function: catch]
}

Otherwise, I can't understand from the docs how to create a "proper" schema that would fall on this. Because if the value would be {} it would fall as expected

Thank you

What I said still applies, it's not required, hence undefined is fine, that's the expected behavior.

Ah, so

    const schema = Joi.object({
        x: Joi.required()
    }).required()
    console.log(Joi.validate(undefined, schema))

would work. Thank you!

Any idea why this doesn't work with Joi.assert()? Trying the schema above.

@jamesdixon works for me, have something for me to run ?

what if I want Joi.validate(undefined, schema) to fail?

Set the root schema as required.

I tried setting root schema to required. I expect it to fail. But it passes validation.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

JbIPS picture JbIPS  路  4Comments

kailashyogeshwar85 picture kailashyogeshwar85  路  4Comments

leore picture leore  路  4Comments

farwayer picture farwayer  路  3Comments

Taxi4you picture Taxi4you  路  3Comments