Strickland
Search…
Validator Factories
Validators often need to be configurable. Instead of always validating that a value matches the letter 'A', our letter validator might need to accept which letter to compare against. To accomplish that, we can define a Validator Factory that accepts props, including the desired letter, and returns a validator to be used.
1
import validate from 'strickland';
2
3
function letterValidator({letter}) {
4
return (value) => value === letter;
5
}
6
7
const validator = letterValidator({letter: 'B'});
8
const result = validate(validator, 'B');
9
10
/*
11
result = {
12
isValid: true,
13
value: 'B'
14
}
15
*/
Copied!
Validator factories merely take advantage of JavaScript's functional nature--in fact, Strickland has no awareness of them. Strickland only requires that validators are functions that accept a value and return a validation result. You can produce those functions however you'd like, but the validator factory approach is a convenient way to extend the functionality of your validators.
Last modified 1yr ago
Copy link