0
votes

When validating strings with Joi, with the following schema:

title: Joi.string().required(),

It's not validating empty strings like the following: " ". I don't think it's correct to repeat string().trim() on every field. How can I validate empty strings? Shouldn't Joi handle this, according to the docs?

Note that the empty string is not allowed by default and must be enabled with allow(''). Don't over think, just remember that the empty string is not a valid string by default. Also, don't ask to change it or argue why it doesn't make sense. This topic is closed.

1
'' and ' ' are two different things, you need to trim in your case. The quote Don't over think, just remember that the empty string is not a valid string by default. is referencing the behaviour you can see between Boolean('') and Boolean(' ') - N.J.Dawson

1 Answers

0
votes

You can use .regex() to validate your fields.

As an example, the following schema will validate any string that only contains spaces (at least one):

const schema = Joi.object({
    a: Joi.string().regex(/^\s+$/)
})

schema.validate({ a: ' ' }) // valid
schema.validate({ a: '     ' }) // valid
schema.validate({ a: '' }) // invalid, adding .allow('') will validate
schema.validate({ a: '1 ' }) // invalid
schema.validate({ a: '11' }) // invalid