Braden Shipley
Braden Shipley

Reputation: 25

Which type of OpenAPI pattern format is valid?

Currently looking at an openapi.yaml that has two different formats for the pattern validator for a string.

    Country:
      pattern: ^(A(D|E|F|G|I|L|M|N|O|R|S|T|Q|U|W|X|Z)|B(A|B|D|E|F|G|H|I|J|L|M|N|O|R|S|T|V|W|Y|Z))$
      type: string
    Currency:
      pattern: /^AED|AFN|ALL|AMD$/
      type: string

The documentation doesn't show / as a boundary character at all, so is this valid or invalid?

I've used the Swagger Editor to input both but neither gives an error.

Upvotes: 1

Views: 1396

Answers (1)

Helen
Helen

Reputation: 97847

The correct format for the pattern is myregex (formatted as a YAML or JSON string, with proper escaping if needed), not /myregex/ or /myregex/flags.

Source: https://github.com/OAI/OpenAPI-Specification/issues/1985

Examples of valid patterns:

# YAML
pattern: \d+      # not anchored
pattern: ^\d+$    # anchored

pattern: '\d+'    # \d+
pattern: "\\d+"   # \d+

# JSON
"pattern": "\\d+"     # \d+
"pattern": "^\\d+$"   # ^\d+$

In your example, the Country pattern is correct, and the Currency pattern is incorrect.

In case of pattern: /^AED|AFN|ALL|AMD$/ (which is equivalent to pattern: "/^AED|AFN|ALL|AMD$/"), the / is considered a part of the pattern string itself, not the boundary character. As a result, this pattern won't match anything because extra characters appear outside of ^...$.

Upvotes: 1

Related Questions