user8479984
user8479984

Reputation: 501

Regex for JSON schema

How to add regex validation for a json schema where the attribute is getting created on the fly and in the format of api pattern and can only contain all upper/lower alphabets, digits, slashes (/) and curly braces {}

E.g:

/someapi/v1/{usename}

/someApi/v1/{userName}

Here is my Uschema:

     {
      "type": "object",
      "patternProperties": {
       "^[a-zA-Z0-9{}/]": {
         "additionalProperties": false,
         "type": "object",
         "patternProperties": {
           "^(EMP|MGR|ACCT)$": {
            "additionalProperties": false,
            "type": "object"
          }
        }
     }
   }
 }

and here is the JSON and the results using ajv (spec 7)

My JSON Sample:

{"/employee/v1/{empId}":{"EMP":{}}} - PASS
{"/employee/v1/{empId}":{"E1MP":{}}} - FAIL (I can understand as E1MP is there)
{"/employee/v1/{empId}/<fooBar>":{"E1MP":{}}} - FAIL 
(I can understand as E1MP is there but didn't complain about < > 
brackets as it was the first entry to validate)

{"/employee/v1/{empId}/<fooBar>":{"EMP":{}}} - PASS (?)
(Actually it should FAIL ???, Why it is considering the < > brackets though I have the regex in place for the outer parent property.)

Also, if I tweak the outer regex to validate any empty space like: ^[a-zA-Z0-9{}/\s], it wont complain any error for the spaces:

{"/emp loye  e/v1/{empI   d}/{f  ooBar}":{"EMP":{}}} -- PASS? (Actually it shoud FAIL ???)

Upvotes: 1

Views: 2701

Answers (1)

Relequestual
Relequestual

Reputation: 12305

There are two problems with your schema.

First, the regex's are not anchored by default. You need to anchor them. Your first regex is not fully anchored.

Second, even when it's fully anchored, you didn't disallow additional properties.

Here's an updated schema:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "additionalProperties": false,
  "patternProperties": {
    "^[a-zA-Z0-9{}/]+$": {
      "additionalProperties": false,
      "type": "object",
      "patternProperties": {
        "^(EMP|MGR|ACCT)$": {
          "additionalProperties": false,
          "type": "object"
        }
      }
    }
  }
}

Now, any property of the object which doesn't match the regex will cause a validation error as you expect.

Upvotes: 2

Related Questions