Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 557
dventi3 Avatar asked Feb 21 '17 15:02

dventi3


People also ask

How do I allow empty strings in Joi?

string(). allow(''). allow(null) should have worked.

Is not allowed to be empty Joi string?

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('').

Which is better express validator or Joi?

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.


2 Answers

You could also specify this with a comma delimited list.

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

See Joi documentation on allow(value)

like image 161
What Would Be Cool Avatar answered Sep 18 '22 09:09

What Would Be Cool


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.

like image 40
Naved Ahmad Avatar answered Sep 21 '22 09:09

Naved Ahmad