Search code examples
javascriptswaggerjsonschema

Restrict values of an array type


It cannot be easier, frankly, however I cannot find the solution anywhere.

I would like to accept an array from the front, with restricted values.

Having the following jsonschema:

const models = {
  type: "string",
  enum: [
    "model1",
    "model2",
    "model3",
  ],
};

const cleanQ = {
  type: "object",
  required: ["models"],
  properties: {
    models: {
      type: "array",
      anyOf: [models],
    },
  },
  additionalProperties: false,
};

I can get an array input type on the front like the following:

enter image description here

that only accepts one single value, and in the back it is transformed as a string value. If I add another correct value, I have the following error:

Request failed validation: Error: querystring/models must be equal to one of the allowed values, querystring/models must match a schema in anyOf.


Solution

  • I think you want an items keyword in there.

    const cleanQ = {
      type: "object",
      required: ["models"],
      properties: {
        models: {
          type: "array",
          items: {
            anyOf: [models]
          }
        },
      },
      additionalProperties: false,
    };
    

    Having type: array is correct to constrain your data to being an array. However the subschemas in anyOf require one of the enum values.

    To specify what the items of the array need to be, you need to use the items keyword.