Strickland
Search…
Arrays of Objects
With the combination of Strickland's objectProps and arrayElements validators, it's easy to validate arrays of objects.
1
import validate, {
2
objectProps, arrayElements, required, length, range, every
3
} from 'strickland';
4
5
const personValidator = objectProps({
6
name: every([required(), length(5, 40)]),
7
addresses: arrayElements(
8
every([
9
required(),
10
objectProps({
11
street: objectProps({
12
number: every([required(), range(1, 99999)]),
13
name: every([required(), length(2, 40)])
14
}),
15
city: required(),
16
state: every([required(), length(2, 2)])
17
})
18
])
19
)
20
});
21
22
const person = {
23
name: 'Marty McFly',
24
addresses: [
25
{
26
street: {
27
number: 9303,
28
name: 'Lyon Drive'
29
},
30
city: 'Hill Valley',
31
state: 'CA'
32
},
33
null,
34
{
35
street: null,
36
city: 'Hill Valley',
37
state: 'CA'
38
}
39
]
40
};
41
42
const result = validate(personValidator, person);
Copied!
Objects can be nested without any limits on depth. And any type of validator can be used anywhere in the tree.
Copy link