hapi icon indicating copy to clipboard operation
hapi copied to clipboard

Joi is insisting that a field should not be empty - why?

Open maxweld opened this issue 5 years ago • 1 comments

Support plan

  • is this issue currently blocking your project? (yes/no): no
  • is this issue affecting a production system? (yes/no): no

Context

  • node version: 14.15.0
  • module version: Joi 17.3.0
  • environment (e.g. node, browser, native): Node
  • used with (e.g. hapi application, another framework, standalone, ...): hapi/Joi
  • any other relevant information:

How can we help?

Why does Joi insist that ""middleNames" is not allowed to be empty" ? I am new to Joi, but believe that this should work. What am I missing. I have tested this both in my app, but also in the Joi.dev Schema Tester with similar results. The data is coming from an HTML Form, but the field in question is intended to be optional and is therefore empty in this case. Thanks in advance..

Schema

Joi.object({
    givenName: Joi.string().required(),
    familyName: Joi.string().required(),
    middleNames: Joi.string(),
    gender: Joi.string(),
    email: Joi.string().required(),
    addr1: Joi.string().required(),
    addr2: Joi.string(),
    addr3: Joi.string(),
    town: Joi.string().required(),
    county: Joi.string().required(),
    postcode: Joi.string().required(),
  }).required()

Data to Validate

{
    familyName: 'Maxwell',
    givenName: 'Susan',
    middleNames: '',
    gender: 'Female',
    email: '[email protected]',
    addr1: '23 Allen Lane',
    addr2: 'West Horribles',
    addr3: 'why not',
    town: 'Wells',
    county: 'Somerset',
    postcode: 'BA5 3HU'
  }

Result

Validation Error: "middleNames" is not allowed to be empty

maxweld avatar Dec 27 '20 23:12 maxweld

What you need is:

middleNames: Joi.string().allow(''),

See Joi String Documentation. The issue of empty strings is addressed at the top.

devinstewart avatar Dec 28 '20 00:12 devinstewart