Compose validation functions into one validator
Compose validation functions into one validator in JavaScript: each rule returns an error or null, and a combinator collects every failing message.
Small rule functions are easy to test. A combinator turns a list of them into one validator that reports all the problems at once.
const required = (v) => (v ? null : 'is required');
const minLength = (n) => (v) => (v.length >= n ? null : `needs ${n}+ characters`);
const noSpaces = (v) => (v.includes(' ') ? 'has spaces' : null);
const validate = (...rules) => (value) =>
rules.map((rule) => rule(value)).filter(Boolean);
const checkPassword = validate(required, minLength(8), noSpaces);
console.log(checkPassword('ab c'));
console.log(checkPassword('longenough'));[ 'needs 8+ characters', 'has spaces' ]
[]Each rule returns null when the value passes and a message when it fails. validate runs all of them and keeps the messages, so the user sees every problem instead of one at a time. Rules like minLength(8) are made by a function that returns a function, and then they compose like any other.
Rules are run even when an earlier one fails. Here required passes for 'ab c', but for an empty string minLength would be called too, so rules that assume a non-empty value should guard themselves or the combinator should stop at the first failure.