Skip to main content
Version: 1.3.0

Array Indexing

You can validate specific elements within arrays using bracket notation. For instance, to validate the first element of the contacts array, use contacts[0]. You can also specify nested properties like user.contacts[0].value.

Example

Request Body

{
"contacts": [
{
"type": "email",
"value": "john.doe@example.com"
},
{
"type": "phone",
"value": "123-456-7890"
}
]
}

Validation Rules

const rules = [
{
key: "user.contacts[0]",
type: "object",
required: true,
},
{
key: "user.contacts[0].type",
type: "string",
required: true,
},
{
key: "user.contacts[0].value",
type: "string",
required: true,
},
];

Explanation

  • key: "user.contacts[0]" targets the first element of the contacts array within the user object.

  • type: "object" indicates that this array element should be an object.

  • required: true means that this array element is mandatory.

  • key: "user.contacts[0].type" validates the type property of the first element in the contacts array.

  • type: "string" specifies that the type should be a string.

  • required: true means that the type property is required.

  • key: "user.contacts[0].value" validates the value property of the first element in the contacts array.

  • type: "string" specifies that the value should be a string.

  • required: true means that the value property is required.