lualover2017
lualover2017

Reputation: 227

Json schema regex

I am building a json request schema at the moment. One of my constraints in the schema is that there value of firstLetter should ONLY contain 1 character, lowercase or uppercase. I tried the following (its a snippet of the schema):

"firstLetter": {
        "id": "/properties/firstLetter",
        "maxLength": 1,
        "minLength": 1,
        "pattern": "[a-z][A-Z]",
        "type": "string"
    }

but it doesn't seem to work. I would also like the regex to have the rule that there should only be 1 character

Upvotes: 1

Views: 3437

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626853

Acc. to 6.8. pattern section of JSON Schema Validation: A Vocabulary for Structural Validation of JSON:

The value of this keyword MUST be a string. This string SHOULD be a valid regular expression, according to the ECMA 262 regular expression dialect.

A string instance is considered valid if the regular expression matches the instance successfully. Recall: regular expressions are not implicitly anchored.

You may use

"pattern": "^[a-zA-Z]$"

It will match exactly 1-letter strings, only consisting of an ASCII letter.

Note that maxLength and minLength become redundant with this regex validation, so you may minify the code to

"firstLetter": {
    "id": "/properties/firstLetter",
    "pattern": "^[a-zA-Z]$",
    "type": "string"
}

Upvotes: 4

Related Questions