pattern : String
pattern
StringA string instance is considered valid if the regular expression matches the instance successfully.
Value | This keyword must be set to a regular expression, preferrably using the ECMA-262 flavour |
---|---|
Kind | Assertion |
Applies To | String |
Base Dialect | 2020-12 |
Changed In | Draft 4 |
Introduced In | Draft 1 |
Vocabulary | Validation |
Specification | https://json-schema.org/draft/2020-12/json-schema-validation.html#section-6.3.3 |
Metaschema | https://json-schema.org/draft/2020-12/meta/validation |
Official Tests | |
Default |
".*"
|
Annotation | None |
Affected By | None |
Affects | None |
Also See |
|
The pattern
keyword restricts string instances to match the given regular
expression.
Digging Deeper
While the specification suggests the use of
ECMA-262
regular expressions for interoperability purposes, the use of different
flavours like PCRE or POSIX (Basic or Extended) is permitted. Also, the
specification does not impose the use of any particular regular expression
flag. By convention (and somewhat enforced by the official JSON Schema test
suite), regular expressions are not implicitly
anchored and are always
treated as case-sensitive. It is also common for the
DOTALL
flag to be enabled, permitting the dot character class to match new lines.
To avoid interoperability issues, stick to ECMA-262, and don’t assume the use of any regular expression flag.
Common Pitfall
Regular expressions often make use of characters that need to be escaped when making use of them as part of JSON strings. For example, the reverse solidus character (more commonly known as the backslash character) and the double quote character need to be escaped. Failure to do so will result in an invalid JSON document. Applications to work with regular expressions, like Regex Forge, typically provide convenient functionality to copy a regular expression for use in JSON.
Remember that JSON Schema is a constraint-driven language.
Therefore, non-string instances successfully validate against this
keyword. If needed, make use of the type
keyword to constraint
the accepted type accordingly.
Examples
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"pattern": "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$"
}
"john.doe@example.com"
"foo"
1234