Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joi, convert empty string to null

Tags:

node.js

joi

I have the following rule: Joi.string().empty("").default(null).

I assumed this rule would convert an empty string "" to null, but that doesn't seem to be the case.

How do I get the desired behavior?

like image 561
Roymunson Avatar asked Oct 22 '25 08:10

Roymunson


2 Answers

There's a slight difference if the rule is to be applied to a non-required field.

Using empty(""): if a request provides "" as the value, it will be replaced with undefined.

Using default(null): means if the value is undefined it will be replaced with null - note that if no value is provided at all in the request it will also be undefined.

So your example will accept any strings, but if the value is "" it will be replaced with undefined, and then if the value is undefined it will be replaced with null.

Therefore the value will always be null for every request, unless a string other than "" is provided.

If you want the value to remain undefined when no value was provided by the request, you need something like:

Joi.alternatives()
  .try(
    Joi.string().valid('').empty('').default(null), // accept only empty strings and convert those to null
    Joi.string() // accept every other string
  )

With this, if the request value is a string it'll be accepted, unless it's "" then it will be converted to null. Otherwise, if the request did not provide any value for the field, the value will remain undefined.

like image 173
Dan D Avatar answered Oct 23 '25 23:10

Dan D


I don't see what's wrong. I get the desired behavior from the provided schema:

const Joi = require('@hapi/joi');

const joiSchema = Joi.string().empty('').default(null);

const { error, value } = joiSchema.validate();
console.log(`error: ${error}`, `value: ${value}`);

Outputs:

"error: undefined"
"value: null"

Make sure you are using the latest version. Check the working code at RunKit: https://runkit.com/rvypandey/5e387545896365001a90a87b

like image 37
Rvy Pandey Avatar answered Oct 23 '25 21:10

Rvy Pandey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!