tdegrunt / jsonschema

JSON Schema validation
Other
1.83k stars 263 forks source link

Validator does not honor "nullable" property for `type: "string", enum: [...]` #397

Closed kael-shipman closed 7 months ago

kael-shipman commented 7 months ago

On version 1.4.1 / node 20

I don't know if this is a problem for other datatypes; I just know it's a problem for string enums.

To reproduce:

const { Validator } = require("jsonschema");

const data = {
  myval: null
}

const schema = {
  type: "object"
  required: ["myval"],
  properties: {
    myval: {
      type: "string",
      enum: ["one", "two"],
      nullable: true,
    }
  }
}

const res = new Validator().validate(data, schema);

// Should not be errors but there are

Current solution is to use oneOf instead:

const schema = {
  type: "object"
  required: ["myval"],
  properties: {
    myval: {
      oneOf: [
        {
          type: "string",
          enum: ["one", "two"],
          nullable: true,
        },
        {
          type: "null",
        },
      ],
    },
  },
}
awwright commented 7 months ago

"nullable" isn't a JSON Schema keyword; I think it's an OpenAPI extension. You're probably looking to add "null" to the list of "type" values:

{ "type": ["object", "null"] }
kael-shipman commented 7 months ago

fwiw I just tried

const schema = {
  type: "object"
  required: ["myval"],
  properties: {
    myval: {
      type: ["string", "null"],
      enum: ["one", "two"],
    }
  }
}

And it still didn't work. But my other work-around works fine, so I'll just use that.