0

I want to validate multiple occurrences of the same query parameter using AJV.

My OpenApi schema looks something like this:

...
/contacts:
  get:
    parameters:
      - name: user_id
        in: query
        schema:
          type: integer
...

I convert it to a valid json schema to be able to validate it with AJV:

{
  query: {
    properties: {
      user_id: { type: 'integer' }
    }
  }
}

Naturally, AJV validation works fine for one parameter of type integer.

I want to be able to validate multiple occurrences of user_id. For example: /contacts?user_id=1&user_id=2 is converted to { user_id: [1, 2] } and I want it to actually be valid.

At this point validation fails because it expects an integer but received an array. Is there any way to validate each items of the array independently ?

Thanks

1

1 Answer 1

0

Perhaps the schema for user_id should use the anyOf compound keywords allowing you to define multiple schemas for a single property:

var ajv = new Ajv({
  allErrors: true
});

var schema = {
  "properties": {
    "user_id": {
      "anyOf": [{
          "type": "integer"
        },
        {
          "type": "array",
          "items": {
            "type": "integer"
          }
        },
      ]
    },
  }
};

var validate = ajv.compile(schema);

function test(data) {
  var valid = validate(data);
  if (valid) console.log('Valid!');
  else console.log('Invalid: ' + ajv.errorsText(validate.errors));
}

test({
  "user_id": 1
});
test({
  "user_id": "foo"
});
test({
  "user_id": [1, 2]
});
test({
  "user_id": [1, "foo"]
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/ajv/6.5.5/ajv.min.js"></script>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.