Strickland
Search…
Validating Objects
We've demonstrated quite a bit of flexibility validating single values with Strickland, including how arrays of validators can be composed together. But every application needs to validate objects. Let's see how Strickland can do this.
We will start by illustrating what object validation looks like with no additional Strickland features. This example will validate a person's first name, last name, and birth year.
1
import validate, {
2
required, length, range, every
3
} from 'strickland';
4
5
// Define the rules for first name, last name, and birthYear
6
const personValidator = {
7
firstName: every([
8
required(),
9
length(2, 20)
10
]),
11
lastName: every([
12
required(),
13
length(2, 20)
14
]),
15
birthYear: range(1900, 2018)
16
};
17
18
// Create a person
19
const person = {
20
firstName: 'Stanford',
21
lastName: 'Strickland',
22
birthYear: 1925
23
};
24
25
// Validate the person's properties
26
const personResult = {
27
firstName: validate(personValidator.firstName, person.firstName),
28
lastName: validate(personValidator.lastName, person.lastName),
29
birthYear: validate(personValidator.birthYear, person.birthYear)
30
};
Copied!
With this example, we have very primitive object property validation. The personResult output includes the validation results for each property, but there isn't anything providing a top-level isValid prop on the results. Let's add that in.
1
// Validate the person's properties
2
const personResult = {
3
firstName: validate(rules.firstName, person.firstName),
4
lastName: validate(rules.lastName, person.lastName),
5
birthYear: validate(rules.birthYear, person.birthYear)
6
};
7
8
// Create a top-level result including the results from personResult
9
const result = {
10
personResult,
11
isValid: (
12
personResult.firstName.isValid &&
13
personResult.lastName.isValid &&
14
personResult.birthYear.isValid
15
),
16
value: person
17
};
Copied!
The top-level result also includes the value to be consistent with the output of other validators.
At this point, we can see a pattern where we would want a validator to iterate over the properties that have validators, validate each of those properties, and compose a final validation result for all props. Indeed, Strickland has such a validator built-in called objectProps.
Copy link