Skip to content

schema: nullable option not working on string with format or pattern #1709

@adrai

Description

@adrai

🐛 Bug Report

Seems there is the option to mark a property in a schema (I tried body schema) as nullable like this:

...
shortbio: { type: 'string', nullable: true },
...

But if the property defines a format or a pattern the nullable option is ignored.

To Reproduce

For example this will not work:

...
website: { type: 'string', nullable: true, pattern: '^(https?:\\/\\/)?(www\\.)?([a-zA-Z0-9]+(-?[a-zA-Z0-9])*\\.)+[\\w]{2,}(\\/\\S*)?$' },
email: { type: 'string', nullable: true, format: 'email' },
...

As a workaround it can be declared like this (see the type value):
For example this will work:

...
shortbio: { type: 'string', nullable: true },
website: { type: ['string', 'null'], nullable: true, pattern: '^(https?:\\/\\/)?(www\\.)?([a-zA-Z0-9]+(-?[a-zA-Z0-9])*\\.)+[\\w]{2,}(\\/\\S*)?$' },
email: { type: ['string', 'null'], nullable: true, format: 'email' },
...

example: https://github.com/adrai/fastify-schema-example

Expected behavior

Expecting this would work:

...
shortbio: { type: 'string', nullable: true },
website: { type: 'string', nullable: true, pattern: '^(https?:\\/\\/)?(www\\.)?([a-zA-Z0-9]+(-?[a-zA-Z0-9])*\\.)+[\\w]{2,}(\\/\\S*)?$' },
email: { type: 'string', nullable: true, format: 'email' },
...

fyi: I want to use the same object schema for body and response.

Your Environment

  • node version: 12.4.0
  • fastify version: 2.5.0
  • os: Mac

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions