Skip to content

trim + empty confuses me #1039

@awilkins

Description

@awilkins

Context

  • node version: 6.9.1
  • joi version: 9.2.0
  • environment (node, browser): node
  • used with (hapi, standalone, ...): just node in a REPL
  • any other relevant information:

What are you trying to achieve or the steps to reproduce ?

Describe your issue here, include schemas and inputs you are validating if needed.

const schema = Joi.string().trim().empty('');
schema.validate(' '); 

Which result you had ?

"value" is not allowed to be empty

What did you expect ?

Successful validation.

trim() states in it's documentation that it edits the field. Intuitively I expected that edit to be applied before the next step in the schema, such that the .empty('') would receive an empty string since the input consisted only of whitespace.

The correct way to do this ... seems to be to pass /\s+/ to .empty()

const schema = Joi.string().empty(/\s+/).trim();
schema.validate(' '); // passes (and value is undefined)

Most of the documentation uses .empty('') though..

Would it break everyone's world if .trim() was applied before other validation.....? Possibly.

At a min. I'd like to see the docs improved to state that

  • Conversions are applied after validations (or whatever the actual behaviour is)
  • Maybe an example or 2 that uses that whitespace regex with .empty() in that context

Metadata

Metadata

Assignees

Labels

featureNew functionality or improvement

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions