Zod-style fluent validators for strings, numbers, and arrays
Libraries such as Zod and Yup let you describe valid data with a fluent API: string().min(2).max(40). In this problem you build a small version of that API for strings, numbers, and arrays.
Implement an object named field with three factory methods. Each returns a validator.
field.string() // a validator for strings
field.number() // a validator for numbers
field.array(item) // a validator for arrays whose elements must pass the validator item
.min(n) and .max(n): add an inclusive lower or upper bound and return a new validator. Strings and arrays compare their length; numbers compare their value..optional(): return a new validator that also accepts undefined..check(value): return an array of issues. An empty array means the value is valid..isValid(value): return true when check(value) finds no issues..min, .max, and .optional never change the validator they are called on, so one base validator can be extended in several directions..min (or .max) again replaces the earlier bound: .min(2).min(5) has a minimum of 5..min(n) and .max(n) throw a TypeError when n is not a finite number (for example '3', NaN, or Infinity).Each issue is an object { code, path }. path is an array of array indexes from the checked value to the failing value: [] for the value itself, [2] for its third element, [1, 0] for the first element of its second element.
'invalid_type': the value has the wrong type. A string must have typeof 'string'. A number must have typeof 'number' and must not be NaN (Infinity is allowed). An array must pass Array.isArray. undefined is an invalid_type unless the validator is optional; null is always an invalid_type.'too_small': below the minimum.'too_big': above the maximum.invalid_type for that value.too_small before too_big. Both can appear if the minimum is greater than the maximum.const username = field.string().min(3).max(12);
username.check('mo'); // => [{ code: 'too_small', path: [] }]
username.check('mira_dev'); // => []
username.check(42); // => [{ code: 'invalid_type', path: [] }]
const rating = field.number().min(1).max(5);
rating.isValid(5); // => true
rating.check(NaN); // => [{ code: 'invalid_type', path: [] }]
const tags = field.array(field.string().min(2)).max(3);
tags.check(['ui', 'x', 'css', 7]);
// => [
// { code: 'too_big', path: [] },
// { code: 'too_small', path: [1] },
// { code: 'invalid_type', path: [3] },
// ]
const nickname = username.optional();
nickname.check(undefined); // => []
username.check(undefined); // => [{ code: 'invalid_type', path: [] }] (username is unchanged)
field.string().min('3'); // throws TypeError