Skip to content

Treat empty string as null #899

@ryan-morris

Description

@ryan-morris

I searched and the closest issue I could find related to my question was #299 . If you feel this is an application level issue only just let me know, but I feel other users of Joi must experience the same type of use case.

We would like to be able to allow empty strings but have Joi convert them to null. Our specific hang up has been around requests in a REST API that feeds both HTML forms and 3rd party partners.

Let's take a user's email address for example. If they specify it then they must make it a valid email address, otherwise if the user omits that field it is not updated. In most cases the user is entering data into a web form of some kind so if they don't want their email in the system any more they clear out the input field and it becomes an empty string.

So we started looking at doing:

var jsonApiInput = {
    email: ''
};

var schema3 = Joi.object().keys({
    email: Joi.string().email().empty('').default(null)
}).required();

schema3.validate(jsonApiInput, function (err, value) {
    //validation ok, { email: null }
});

and this works fine except when a 3rd party implementer omits that field, it defaults to null, and values they did not expect to be updating are nulled in the database.

Right now our only option is to if(obj.email == '') { obj.email = null } all of our string fields either after Joi has validated the object (leaving .default(null) off), or on all the client side versions.

Ideally, we could do something like .empty('', null) to set the assigned empty value, or some kind of conditional default value.

Does anyone have any thoughts or suggestions on use cases like this?

Metadata

Metadata

Assignees

Labels

featureNew functionality or improvement

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions