hapijs / joi

The most powerful data validation library for JS
Other
20.92k stars 1.51k forks source link

validate undefined doesn't return error #717

Closed neroaugustus1 closed 9 years ago

neroaugustus1 commented 9 years ago

schema: { name: joi.string().required() }

if you pass in undefined to validate with this schema you don't get an error. Is this on purpose? If you accidentally try and validate an undefined value against a schema that requires a name you should get an error.

mtharrison commented 9 years ago

From the docs:

any.required() Marks a key as required which will not allow undefined as value. All keys are optional by default.

If you want it to be required, you need to specify that explicitly:

Joi.assert(undefined, Joi.object().keys({ name: Joi.string().required() }).required())
Error: {
  "value" [1]: -- missing --
}

[1] "value" is required
neroaugustus1 commented 9 years ago

But with null you get an error. Maybe it's how it's supposed to work, but it feels very counterintuitive. When would you ever want to validate undefined against a schema and have it pass successfully?

hueniverse commented 9 years ago

That's because your actual schema is an optional object. The fact that this optional object has a required key is irrelevant to what you are testing. If the object itself is required, you need to make the root object required as shown by @mtharrison.

Marsup commented 9 years ago

Maybe hapi should set required by default if it's a POJO, that's what most people expect.