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 thecontacts
array within theuser
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 thetype
property of the first element in the contacts array. -
type
:"string"
specifies that thetype
should be a string. -
required
:true
means that thetype
property is required. -
key
:"user.contacts[0].value"
validates thevalue
property of the first element in the contacts array. -
type
:"string"
specifies that thevalue
should be a string. -
required
:true
means that thevalue
property is required.