Skip to content

Commit

Permalink
add description and examples for const keyword (#107)
Browse files Browse the repository at this point in the history
This PR addresses #87.
  • Loading branch information
AgniveshChaubey authored Feb 8, 2024
1 parent c50ec56 commit 6108369
Showing 1 changed file with 60 additions and 0 deletions.
60 changes: 60 additions & 0 deletions content/2020-12/validation/const.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,63 @@ related:
- vocabulary: validation
keyword: type
---

The `const` keyword in restricts an instance to a specific value. Its usage is functionally similar to an `enum` with a single value. Instances validate successfully only if their property value deeply matches the specified constant.

* Applies to various JSON data types, including numbers, strings, booleans, objects, and arrays.
* Takes precedence over other validation keywords like `type` and `enum`.

{{<alert>}}
_**Note:** It is best practice to avoid using the `type` keyword or any other validation keyword with `const`, as `const` takes precedence over them. Therefore, it is better not to use them together._
{{</alert>}}

## Examples

{{<schema `Schema with a specific string value`>}}
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"const": "hello"
}
{{</schema>}}

{{<instance-pass `An instance matching the const value is valid`>}}
"hello"
{{</instance-pass>}}

{{<instance-fail `An instance not matching the const value is invalid.`>}}
"world"
{{</instance-fail>}}

{{<schema `Schema with a specific number value`>}}
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"const": 3.14159
}
{{</schema>}}

{{<instance-pass `An instance matching the const value is valid`>}}
3.14159
{{</instance-pass>}}

{{<instance-fail `An instance not matching the const value is invalid.`>}}
"pi"
{{</instance-fail>}}

{{<schema `Schema with a fixed object structure`>}}
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"const": { "name": "John Doe", "age": 30 }
}
{{</schema>}}

{{<instance-fail `An empty object is invalid`>}}
{}
{{</instance-fail>}}

{{<instance-pass `An instance matching the exact object structure is valid`>}}
{ "name": "John Doe", "age": 30 }
{{</instance-pass>}}

{{<instance-fail `An instance not matching the exact object structure is invalid`>}}
{ "name": "Robert", "age": 30 }
{{</instance-fail>}}

0 comments on commit 6108369

Please sign in to comment.