jhthorsen / json-validator

:cop: Validate data against a JSON schema
https://metacpan.org/release/JSON-Validator
57 stars 59 forks source link

anyOf + required doesn't seems to work #118

Closed cashlo closed 6 years ago

cashlo commented 6 years ago

Here's a simple test:

use strict;
use warnings;

use JSON::Validator;
use Data::Printer;

my $v = JSON::Validator->new;
$v->schema(
    {   'anyOf' => [
            { 'required' => ['test_number'] },
            { 'required' => ['test_string'] },
        ],
        'properties' => {
            'test_number' => { 'type' => 'number' },
            'test_string' => { 'type' => 'string' },
        },
        'type' => 'object',
    }
);

my $j = { test_something_else => 'aaa' };

my @result = $v->validate($j);
p @result;

I am expecting a error here, but I get no error. If I switch to oneOf, I get "All of the oneOf rules match.".

Am I missing something here?

jhthorsen commented 6 years ago

I don't understand your schema. How do you expect it to work, when you have "anyOf", "type" and "properties" at the same level?

Have you validated your schema? It does not look valid.

cashlo commented 6 years ago

https://www.jsonschemavalidator.net/ takes it fine.

Another way to put it is like this, which works fine:

$v->schema(
    {   'anyOf' => [
            {   'required'   => ['test_number'],
                'type'       => 'object',
                'properties' => {
                    'test_number' => { 'type' => 'number' },
                    'test_string' => { 'type' => 'string' }
                }
            },
            {   'required'   => ['test_string'],
                'type'       => 'object',
                'properties' => {
                    'test_number' => { 'type' => 'number' },
                    'test_string' => { 'type' => 'string' }
                }
            },
        ],
    }
);
jhthorsen commented 6 years ago

The schema below gives me 3 error with draft4:

{
  "type": "object",
  "properties": { "test_number": { "type": "number" }, "test_string": { "type": "string" } },
  "anyOf": [
    { "required": [ "test_number" ] },
    { "required": [ "test_string" ] }
  ]
}

How are you able to validate it with zero errors? A screenshot works for me...

cashlo commented 6 years ago

You mean for the schema itself? screen shot 2018-10-08 at 11 45 09 am

cashlo commented 6 years ago

Or like this? Not too sure how this works screen shot 2018-10-08 at 11 56 18 am

jhthorsen commented 6 years ago

Thanks for the screenshots! It's so weird, but I sometimes get "three errors" when pasting in your schema, but I tried doing some manual changes and then it got validated... Very strange.

Anyways, this is now fixed in 29f34585920c6c6bb6fc3b03b25b15431109d820, but you can fix it manually by adding type=>'object' while waiting for the new release.