1

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

3
  • 1
    Try "^[a-zA-Z]$" or (if it is used in XSD Schema later) "[a-zA-Z]" Commented May 5, 2017 at 10:22
  • 1
    Or use [a-zA-Z]{1} it matches a single character. Commented May 5, 2017 at 10:41
  • @lualover, did my answer work for you? If yes, please consider accepting. Else, please let know of the results. Commented May 5, 2017 at 18:05

1 Answer 1

4

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"
}
Sign up to request clarification or add additional context in comments.

3 Comments

So would the schema throw a validation error if for example someone sent a request like "firstLetter":"ab"
I updated the pattern as per this JSON Schema 1.0 documentation and JSON Schema.
Now, I think it is complete. Sorry, I just mistook the JSON schema with XML Schema at first.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.