Allow string to be null or empty in joi and express-validation

dventi3 picture dventi3 · Feb 21, 2017 · Viewed 19.2k times · Source

I am using "joi": "10.0.6" and "express-validation": "1.0.1" in my project to validate a JSON object which I will save in the DB. One of the field is a string but it could be null or empty. How can I allow my string to pass the validation in the cases it is empty or null?

I have already tried these cases:

dataId: Joi.string().allow(null).allow('').optional()

and

dataId: Joi.alternatives().try(Joi.string(), Joi.allow(null))

but both them don't work.

Answer

What Would Be Cool picture What Would Be Cool · Mar 30, 2018

You could also specify this with a comma delimited list.

dataId: Joi.string().allow(null, '')

See Joi documentation on allow(value)