Skip to content

Commit

Permalink
update code and instructions
Browse files Browse the repository at this point in the history
  • Loading branch information
JeelRajodiya committed May 30, 2024
1 parent 7edf236 commit 3ab48c1
Show file tree
Hide file tree
Showing 2 changed files with 145 additions and 0 deletions.
88 changes: 88 additions & 0 deletions content/01-introduction/05-Enumerated-Values/code.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
const code: any = {
type: "object",
properties: {
name: {
type: "string",
},
age: {
type: "number",
},
},
};

const solution = structuredClone(code);
solution.properties.role = {
enum: ["employee", "manager", "admin"],
};

const validationSchema = {
type: "object",
properties: {
type: {
type: "string",
const: "object",
},
properties: {
type: "object",
properties: {
name: {
type: "object",
properties: {
type: {
type: "string",
const: "string",
},
},
required: ["type"],
},
age: {
type: "object",
properties: {
type: {
type: "string",
const: "number",
},
},
required: ["type"],
},
role: {
type: "object",
properties: {
enum: {
type: "array",
items: {
allOf: [
{
anyOf: [
{
const: "employee",
},
{
const: "manager",
},
{
const: "admin",
},
],
},
{
type: "string",
},
],
},
},
},
required: ["enum"],
},
},
required: ["name", "age", "role"],
},
},
required: ["type", "properties"],
};

module.exports = {
code,
solution,
validationSchema,
};
57 changes: 57 additions & 0 deletions content/01-introduction/05-Enumerated-Values/instructions.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
---
title: "Enumerated values"
description: "Constrain the value of a property to a fixed set of values using JSON Schema."
keywords: "enum"
---

# Enumerated values

In the previous step, we have learned to define a constant value for a property using the `const` keyword. However a role of an employee can not be just `employee` it can be also `manager`, `admin` etc.

We want to constrain the value of the `role` property to a fixed set of values which are `employee`, `manager` and `admin`.


**For Example:** both of these values for role is valid in the below data
```json highlightLineStart={4}
{
"name": "John Doe ",
"age": 25,
"role": "manager"
}
```
```json highlightLineStart={4}
{
"name": "John Doe ",
"age": 25,
"role": "admin"
}
```



We can use the `enum` keyword to define this fixed set of values for a property.

## Schema Definition

Here is how we can define the `role` property in the schema with the type `string` and the fixed set of values `employee`, `manager` and `admin`.

```json
{
...
"role": {
"enum": ["employee", "manager", "admin"]
}
}
```



<GoodToKnowBox>

The values passed to the `const` keyword are **case-sensitive**.

`"const": "employee"` is valid

`"const": "Employee"` is **in**valid

</GoodToKnowBox>

0 comments on commit 3ab48c1

Please sign in to comment.