Joi: Add an option to allow null values

Created on 1 Dec 2014  Â·  9Comments  Â·  Source: sideway/joi

I'm facing an issue with dates, where I want to validate dates, but the value (not key) should be optional, and therefore null should be allowed.

Validation object:

var Joi = require('joi');

var schema = Joi.object().keys({
    date: Joi.date().optional()
});

Example 1:

Joi.validate({ }, schema, function (err, value) { }).error === null; // true

Example 2:

Joi.validate({date: '2014-10-28T00:00:00+0100'}, schema, function (err, value) { }).error === null; // true

Example 3:

Joi.validate({date: null}, schema, function (err, value) { }).error === null; // false;

I'd expect the Example 3 to not return any error, since I declared dates as optional.

Possible solutions:

Change optional behaviour

https://github.com/hapijs/joi/blob/master/lib/any.js#L334

if (value === undefined || value === null) {

I think optional, forbidden etc. are the only options, which refer to the key, not the value. But also this would be a big change for all users of this library.

Add a null() validator

Add a new validator for null values.

Joi.object().keys({
    date: Joi.date().null()
});

Add a null() validator option 2

Add a new validator for null values.

Joi.object().keys({
    date: Joi.alternatives().try(Joi.date(), Joi.null())
});

I'd be happy to get feedback before making the code change & opening a PR. Thanks.

non issue

Most helpful comment

Use Joi.date().allow(null).

All 9 comments

Added another null() validator option, working with alternatives/try.

Use Joi.date().allow(null).

Oh, I didn't get that. Thanks! :bow:

It would be nice to have a global option to treat null as undefined since many databases return null instead of undefined and when you try to save it again it won't pass validation.

@tuhoojabotti Doesn't your ORM already provide a nice serialization that will strip the null values ?

There would be this https://github.com/brianc/node-pg-types but PostgreSQL doesn't have a type for null so I can't do automatic null stripping that way. Also it seems wasteful to process all fields every time on read when it could be done once on write. I'm using Bookshelf.js, maybe in the next project I'll be able to use hapi.

That should be part of the docs…

What should be ? PR if you feel something's missing.

Nvm. Just realized it actually _is_ in the docs.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

PaunPrashant picture PaunPrashant  Â·  3Comments

sergibondarenko picture sergibondarenko  Â·  3Comments

kevbook picture kevbook  Â·  4Comments

Taxi4you picture Taxi4you  Â·  3Comments

n-sviridenko picture n-sviridenko  Â·  3Comments