Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

OneOf validation issue #2412

Closed
SypMinh opened this issue Apr 9, 2024 · 1 comment
Closed

OneOf validation issue #2412

SypMinh opened this issue Apr 9, 2024 · 1 comment
Labels

Comments

@SypMinh
Copy link

SypMinh commented Apr 9, 2024

What version of Ajv are you using? Does the issue happen if you use the latest version?
ajv: "8.12.0"
Ajv options object

  const ajv = new Ajv({
    allErrors: true,
    multipleOfPrecision: 1,
  });

JSON Schema

const eventSchema = {
  type: 'object',
  properties: {
    oneProperty: {
      oneOf: [
        {
          type: 'object',
          properties: {
            absolute: {
              type: 'number',
              minimum: 1,
              maximum: 16,
              multipleOf: 1,
            },
          },
        },
        {
          type: 'object',
          properties: {
            relative: {
              type: 'number',
              minimum: -8,
              maximum: 8,
              multipleOf: 1,
            },
          },
        },
      ],
    },
  },
  required: ['oneProperty'],
};

Sample data

{
    "oneProperty": {
        "absolute": "-1"
    }
}

Your code

const validateRequestParams = (
  requestParams,
  eventSchema
) => {
  const ajv = new Ajv({
    allErrors: true,
    multipleOfPrecision: 1,
  });
  const validate = ajv.compile(eventSchema);
  const valid = validate(requestParams ?? {});
  if (!valid) {
    return false;
  }
  return true;
};

Validation result, data AFTER validation, error messages
true

What results did you expect?
false

@SypMinh SypMinh changed the title OneOf validation issue when OneOf validation issue Apr 9, 2024
@jasoniangreen
Copy link
Collaborator

The problem is that the second schema you have defined does not prevent additionalProperties, nor does it "require" a property of relative. Therefore it passes as true for the second schema in the oneOf. If you want this to fail either make additionalProperties false or add required.

These are common mistakes when working with JSON Schema.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Development

No branches or pull requests

2 participants