Search code examples
openapijsonschemaajv

JSON Schema — Validate against multiple nullable schemas?


I'm trying to validate null against the schema below:

{
  oneOf: [
    { type: "string", nullable: true },
    { type: "number", nullable: true },
  ]
}

I was expecting the validation to be a success, but it wasn't. Without oneOf (so with just one schema but still with nullable: true) the validation passes.

Here is my sample code:

import Ajv from "ajv";
const ajv = new Ajv();
const schema = {
  oneOf: [
    { type: "string", nullable: true },
    { type: "number", nullable: true },
  ],
};

const data = null;
const validate = ajv.compile(schema);
const valid = validate(data);
if (!valid) {
  console.log(validate.errors);
} else {
  console.log("Validation Success");
}

Im using [email protected] and open api specification 3.0


Solution

  • Change oneOf to anyOf. The reason it fails is because oneOf requires the data to match exactly one schema, however null will match both.