55

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.

dventi3
  • 901
  • 4
  • 11
  • 19

6 Answers6

90

You could also specify this with a comma delimited list.

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

See Joi documentation on allow(value)

What Would Be Cool
  • 6,204
  • 5
  • 45
  • 42
  • I try to do the same using Express-validator/validator.js, any idea how to check for null and validates this correctly? https://github.com/chriso/validator.js https://github.com/express-validator/express-validator – Melroy van den Berg Apr 21 '18 at 21:16
  • I haven't used that library before, but looks like you could do so with a custom validator. https://github.com/express-validator/express-validator#customvalidator – What Would Be Cool Apr 22 '18 at 22:52
  • Yea I though the same, however the docs says: "Returns: the current validation chain instance". But I can't return 'null', since Express validator says it can't return null :S. – Melroy van den Berg Apr 24 '18 at 21:29
28

It's very simple, suppose the field is data then you could impose the validation as

data: Joi.string().allow('')

allowing empty string to pass, for multiple string validation it could also be done as

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

allowing both empty as well as null value for the data field to pass.

Naved Ahmad
  • 783
  • 8
  • 7
8

If you want to allow the empty string and treat it the same as undefined (i.e., convert it to undefined), then use Joi's empty method:

data: Joi.string().empty('')
Josh Kelley
  • 56,064
  • 19
  • 146
  • 246
5

Joi.string().allow('').allow(null) should have worked. I tested locally and it works fine.

Show your test cases and errors?

Dao Lam
  • 2,837
  • 11
  • 38
  • 44
4

If you just specify it as

dataId: Joi.string()

it should be optional per default.

EDIT: Could not try it on my own currently. Here an alternative, if above does not work:

dataId: Joi.string().min(0).allow('').allow(null)
Marc
  • 1,900
  • 14
  • 22
3

If you need only null or empty string use this:

 dataId: Joi.string().valid(null, '')
Poçi
  • 243
  • 3
  • 8