skip to Main Content

I have a schema trying to validate a port number and it is being compared to a reference to a port definition and a constant value of negative 1.

When evaluating a port value (21915) it says th at the value is valid under each of the the checks mentioned above (const and port).

I have changed the value to be 0 and -1 and it does not complain, but once it’s bigger than 0 it starts the issue again.

Port is defined as follows in a separate file:

...
"port": {
"type": "number",
"multipleOf": 1.0,
"minimum": 1,
"maximum": 65535
},
....

The way the check is set up is as follows:

"oneOf": [
     {"$ref": "schemaFile.json#/port"},
     {"const": -1},
     {"type": "null"}
]

Error says:

21915.0 is valid under each of {"const": -1}, {"$ref": "schemaDef.json#/port"}

2

Answers


  1. Your schema is correct. I suspect that the problem is that you’re using a validator that doesn’t support the const keyword. const was added in JSON Schema draft-06, so if you’re validator is way back on draft-04, you might get this error. Unknown keywords are ignored, so that subschema effectively has no constraints and will always pass. Therefore, if the value passes the first or third schema, you’ll always get an error for oneOf because more than one of the subschemas are passing.

    Assuming that I’m right that you’re on draft-04, you can use "enum": [-1] in place of "const": -1 and things should work as you expect.

    Login or Signup to reply.
  2. You have competing constraints on the port definition and the oneOf

    const: -1 contradicts your minimum and maximum but otherwise, the schema seems to pass your requirements.

    passing instances

    {
    "port": 1
    }
    
    # I don't think you expect this but the const -1 overrides the min/max constraints
    {
    "port": -1
    }
    
    {
    "port": 21965
    }
    
    {
    "port": null
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search