Strickland
Search…
Arrays of Validators
Values often need to be validated against multiple validators. This can be represented in Strickland by using arrays of validators with a top-level validator that operates over the array. The top-level validator can invoke the validate function to collect results from each validator and combine the results into a top-level validation result.
Here is a validator that validates every validator in an array, short-circuiting as soon as an invalid result is encountered.
1
import validate from './strickland';
2
3
export default function every(validators) {
4
return function validateEvery(value, context) {
5
let result = {
6
value,
7
isValid: true
8
};
9
10
validators.every((validator) => {
11
let validatorResult = validate(
12
validator, value, context
13
);
14
15
result = {
16
...result,
17
...validatorResult,
18
isValid: validatorResult.isValid
19
};
20
21
return result.isValid;
22
});
23
24
return result;
25
}
26
}
Copied!
The every validator uses the factory pattern, accepting an array of validators and returning a function to validate every one of the validators. Because validators can accept validation context, those must be accepted and passed through.
Here is how the every validator can be used.
1
import validate, {every, required, minLength} from 'strickland';
2
3
const mustExistWithLength5 = every([
4
required(),
5
minLength(5)
6
]);
7
8
const result = validate(mustExistWithLength5, '1234', {
9
message: 'Must have a length of at least 5'
10
});
11
12
/*
13
result = {
14
isValid: false,
15
value: '1234',
16
required: true,
17
minLength: 5,
18
length: 4
19
}
20
*/
Copied!

Built-In Composition Validators

Strickland has a few built-in composition validators that operate over arrays of validators.
  • every
    • Returns a valid result if all validators are valid
    • Short-circuits upon the first invalid result
  • all
    • Returns a valid result if all validators are valid
    • Does not short-circuit, producing results for all validators
  • some
    • Returns a valid result if any validator is valid
    • Short-circuits upon the first valid result
Last modified 1yr ago