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 valid ECMA-262 regular expression |
---|---|
Kind | Assertion |
Applies To | String |
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 in JSON Schema is designed to define a regular expression pattern that a string value within an instance must adhere to. This regular expression is specified as a string for the pattern
keyword. It functions as follows:
- A string value is considered valid only if it successfully matches the specified pattern.
- The regular expressions used with
pattern
are not implicitly anchored, requiring a complete match for validation. Partial matches are not accepted.
Examples
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "string",
"pattern": "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$"
}
"john.doe@example.com"
"invalid@yahoo"
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "string",
"pattern": "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)[a-zA-Z\\d]{8,}$"
}
"MyStrongPass89"
"password"
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "string",
"pattern": "^[a-zA-Z0-9_]+$",
"minLength": 5,
"maxLength": 15
}
"foo_bar123"
"invalid#username"
"username_toolong123"
- This keyword can be combined with other string-related keywords, such as
maxLength
andminLength
, for comprehensive validation.
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "string",
"pattern": "apple"
}
"apple"
"I love apples!"
-
When defining regular expressions, it’s crucial to note that a string is considered valid if the expression matches anywhere within it, as demonstrated in the above example.
-
To avoid this and ensure that the entire string exactly matches the
pattern
, you would surround the regular expression with^
and$
. See the example below.
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "string",
"pattern": "^apple$"
}
"apple"
"I love apples!"