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.
string(). allow(''). allow(null) should have worked.
empty strings are not allowed by default and must be enabled with allow('') . However, if you want to specify a default value in case of empty string you have to use a different pattern: Joi. string(). empty('').
Joi can be used for creating schemas (just like we use mongoose for creating NoSQL schemas) and you can use it with plain Javascript objects. It's like a plug n play library and is easy to use. On the other hand, express-validator uses validator. js to validate expressjs routes, and it's mainly built for express.
You could also specify this with a comma delimited list.
dataId: Joi.string().allow(null, '')
See Joi documentation on allow(value)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With