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 thecontactsarray within theuserobject. -
type:"object"indicates that this array element should be an object. -
required:truemeans that this array element is mandatory. -
key:"user.contacts[0].type"validates thetypeproperty of the first element in the contacts array. -
type:"string"specifies that thetypeshould be a string. -
required:truemeans that thetypeproperty is required. -
key:"user.contacts[0].value"validates thevalueproperty of the first element in the contacts array. -
type:"string"specifies that thevalueshould be a string. -
required:truemeans that thevalueproperty is required.