joi-browser icon indicating copy to clipboard operation
joi-browser copied to clipboard

Not allowing empty string

Open Gilbert1391 opened this issue 6 years ago • 4 comments

It seems like joi browser does not allow to have empty string. This is my schema:

schema = {
    _id: Joi.string(),
    heading: Joi.string()
      .min(5)
      .max(50)
      .label("Heading")
      .required(),
    subHeading: Joi.string().max(50)
  };

If I leave the subHeading field empty (because it is not a required field) I get an error: ""subHeading" is not allowed to be empty"

Is there anyways to allow empty string in the validation?

Gilbert1391 avatar Jan 05 '19 23:01 Gilbert1391

You should probably look at joi docs for joi usage, not here. The answer is Joi.string().allow('').

Marsup avatar Jan 06 '19 14:01 Marsup

You should probably look at joi docs for joi usage, not here. The answer is Joi.string().allow('').

Yeah I tried that and for some reason I'm getting a 400 bad request. I am using Node.js for the back-end and I made sure that this field is not required in my modal, something I can confirm using Postman. This must be a joi related issue (or something else is wrong with my code). When catch the error.response and print it on the console I get the following object:

{data: ""subHeading" is not allowed to be empty", status: 400, statusText: "Bad Request", headers: {…}, config: {…}, …}

The message is the same I was getting in the errors object before using .allow('')

Gilbert1391 avatar Jan 06 '19 17:01 Gilbert1391

Ok I solved the issue. In my back-end joi validation schema I had to add allow("") and then I also had to add the same piece of code in my front-end joi-browser validation schema.

It is weird though... How come using Postman I was not getting any errors when passing an empty string, the joi validation should've thrown an error because I didn't specify allow('')

Gilbert1391 avatar Jan 06 '19 18:01 Gilbert1391

Hard to tell without code.

Marsup avatar Jan 06 '19 19:01 Marsup