Putting functions together: a validator library
This is the last lesson of the part, and it builds one small library of ordinary JavaScript out of everything the part taught. A validator takes a record and returns the list of things that are wrong with it. The rules are functions that return functions, the settings are an options object, the validator is pure, and the report is counted with map, filter and reduce.
The design choice that holds it together is the return value of a rule: null when the value is fine and a message when it is not. A rule never throws for a record the user typed, so a validator can run every rule and report all the problems at once, and a program that needs only the first one can say so with an option.
Rules as functions
A rule is a function of one value with two possible answers by convention: null for a value it accepts and a string for one it rejects. The two rules below are written as factories, so a call configures a rule and returns it: minLength(3) is a rule, and minLength(5, "too short") is the same rule with a message of its own.
function required(message = 'is required') {
return (value) => (value === undefined || value === null || value === '' ? message : null);
}
function minLength(length, message = `must be at least ${length} characters`) {
return (value) => (typeof value === 'string' && value.length >= length ? null : message);
}
const isName = required();
const isLongName = minLength(3);
console.log('empty name:', isName(''));
console.log('given name:', isName('ada'));
console.log('short name:', isLongName('ab'));
console.log('long name:', isLongName('ada'));
console.log('a number is not a name:', isLongName(42));
console.log('a custom message:', minLength(5, 'too short')('abc'));
node rules.js
empty name: is required
given name: null
short name: must be at least 3 characters
long name: null
a number is not a name: must be at least 3 characters
a custom message: too short
Every rule is a small function that can be called in a test with one value, and the factories make the configuration read as a sentence. null as the success value is the convention that makes the loop of the next section possible: a rule either says nothing or says what is wrong, and a message is a value that can be collected. The number 42 is not a name, and minLength says so instead of throwing on value.length.
A schema and a validator
A schema is an object whose keys are the fields of a record and whose values are arrays of rules. The validator walks the fields, runs every rule for each, and collects the messages together with the name of the field. Two options change the behaviour: the fields to check, which makes one validator serve two forms, and stopAtFirst, which returns as soon as one field has failed.
function required(message = 'is required') {
return (value) => (value === undefined || value === null || value === '' ? message : null);
}
function minLength(length, message = `must be at least ${length} characters`) {
return (value) => (typeof value === 'string' && value.length >= length ? null : message);
}
function oneOf(allowed, message = `must be one of ${allowed.join(', ')}`) {
return (value) => (allowed.includes(value) ? null : message);
}
const schema = {
name: [required(), minLength(3)],
role: [required(), oneOf(['admin', 'editor'])],
email: [required()],
};
function validate(record, fields, { stopAtFirst = false } = {}) {
const errors = [];
for (const field of Object.keys(fields)) {
for (const rule of fields[field]) {
const message = rule(record[field]);
if (message !== null) {
errors.push(`${field} ${message}`);
if (stopAtFirst) {
return errors;
}
}
}
}
return errors;
}
const good = { name: 'ada', role: 'admin', email: 'ada@example.com' };
const bad = { name: 'ab', role: 'guest' };
console.log('good:', JSON.stringify(validate(good, schema)));
console.log('bad:', validate(bad, schema).join('; '));
console.log('first error only:', validate(bad, schema, { stopAtFirst: true }).join('; '));
console.log('errors found:', validate(bad, schema).length);
node schema.js
good: []
bad: name must be at least 3 characters; role must be one of admin, editor; email is required
first error only: name must be at least 3 characters
errors found: 3
The good record produced an empty array, which is the success value of the whole validator. The bad one produced three messages, one per rule that failed, and every message names its field so that a form can put it next to the input. The option returns the first message alone, and the full call still finds all three, because a validator that throws on the first problem can never show a user the second.
Normalise, then validate
A record from a form arrives with spaces and capitals that the rules do not expect. The answer is a step before validation, not a rule that trims: a normalise function built from a list of fields and a text transform, put together with the pipe of the previous lessons. The step is pure, so the record the caller holds is unchanged.
function required(message = 'is required') {
return (value) => (value === undefined || value === null || value === '' ? message : null);
}
function oneOf(allowed, message = `must be one of ${allowed.join(', ')}`) {
return (value) => (allowed.includes(value) ? null : message);
}
const schema = {
name: [required()],
role: [required(), oneOf(['admin', 'editor'])],
};
function validate(record, fields) {
const errors = [];
for (const field of Object.keys(fields)) {
for (const rule of fields[field]) {
const message = rule(record[field]);
if (message !== null) {
errors.push(`${field} ${message}`);
}
}
}
return errors;
}
const raw = { name: ' ada ', role: ' ADMIN ' };
console.log('before:', validate(raw, schema).join('; '));
function normaliseFields(fields, transform) {
return (record) =>
fields.reduce((current, field) => {
const value = current[field];
if (typeof value !== 'string') {
return current;
}
return { ...current, [field]: transform(value) };
}, record);
}
function pipe(...functions) {
return (value) => functions.reduce((current, fn) => fn(current), value);
}
const normalise = pipe(
normaliseFields(['name', 'role'], (text) => text.trim()),
normaliseFields(['role'], (text) => text.toLowerCase()),
);
console.log('normalised:', JSON.stringify(normalise(raw)));
console.log('after:', JSON.stringify(validate(normalise(raw), schema)));
console.log('the original object is untouched:', JSON.stringify(raw));
node normalise.js
before: role must be one of admin, editor
normalised: {"name":"ada","role":"admin"}
after: []
the original object is untouched: {"name":" ada ","role":" ADMIN "}
Before the step the role ADMIN failed the rule that allows the lower-case word, and after it the record passed. The original object still holds the spaces and the capitals, because every step of the normaliser built a new object with the spread syntax. The two transforms are separate steps in a pipe, which is what makes the order visible: trimming first and lowering after, or the other way round, gives the same text here and is a decision the reader can see.
The library in use
The last program wraps the validator in a factory with two options, normalisation and stopAtFirst, and runs four records through it. The counts at the end are a map to the number of errors, a filter for the valid ones and a reduce for the total, which is the whole of the previous lessons in six lines.
function required(message = 'is required') {
return (value) => (value === undefined || value === null || value === '' ? message : null);
}
function minLength(length, message = `must be at least ${length} characters`) {
return (value) => (typeof value === 'string' && value.length >= length ? null : message);
}
function oneOf(allowed, message = `must be one of ${allowed.join(', ')}`) {
return (value) => (allowed.includes(value) ? null : message);
}
const schema = {
name: [required(), minLength(3)],
role: [required(), oneOf(['admin', 'editor'])],
email: [required()],
};
function validate(record, fields, { stopAtFirst = false } = {}) {
const errors = [];
for (const field of Object.keys(fields)) {
for (const rule of fields[field]) {
const message = rule(record[field]);
if (message !== null) {
errors.push(`${field} ${message}`);
if (stopAtFirst) {
return errors;
}
}
}
}
return errors;
}
function normaliseRecord(record) {
const name = typeof record.name === 'string' ? record.name.trim() : record.name;
const role = typeof record.role === 'string' ? record.role.trim().toLowerCase() : record.role;
return { ...record, name, role };
}
function makeValidator(fields, { stopAtFirst = false, normalise = (record) => record } = {}) {
return (record) => validate(normalise(record), fields, { stopAtFirst });
}
const validateUser = makeValidator(schema, { normalise: normaliseRecord });
const checkFirst = makeValidator(schema, { normalise: normaliseRecord, stopAtFirst: true });
const records = [
{ name: 'ada', role: 'admin', email: 'ada@example.com' },
{ name: ' ab ', role: ' EDITOR ', email: 'ab@example.com' },
{ name: 'grace', role: 'guest' },
{ name: 'alan', role: 'editor', email: 'alan@example.com' },
];
for (const record of records) {
const errors = validateUser(record);
console.log(`${record.name}: ${errors.length === 0 ? 'ok' : errors.join('; ')}`);
}
const counts = records.map((record) => validateUser(record).length);
console.log('errors per record:', counts.join(','));
console.log('valid records:', counts.filter((count) => count === 0).length, 'of', records.length);
console.log('errors in total:', counts.reduce((total, count) => total + count, 0));
console.log('with stopAtFirst:', JSON.stringify(checkFirst(records[2])));
node library.js
ada: ok
ab : name must be at least 3 characters
grace: role must be one of admin, editor; email is required
alan: ok
errors per record: 0,1,2,0
valid records: 2 of 4
errors in total: 3
with stopAtFirst: ["role must be one of admin, editor"]
The record with the spaces failed because the name is two characters after trimming, which is the kind of detail a validator exists to report. Grace has two problems and the second validator reports only the first, as an options object asked it to. Nothing in the library reads a clock, a file or a global, so every line of the output is decided by the records in the file, and the whole thing is about a hundred lines of ordinary functions. That is the part: rules that return functions, a pipeline that prepares a value, and a report built with the array methods.
Exercises
- Add a rule maxLength(10) to rules.js and a case that fails it. Which value does the rule return for a valid string?
- Add a password field to the schema in schema.js with minLength(8). Which of the two records fails now, and how many errors are reported?
- Replace stopAtFirst: true in library.js with a version that returns the errors of the first failing field and not just the first error. Which record changes its output?
- Move the required rule after minLength for the name in schema.js. Which message does a record with an empty name get?
- Add a normalise step that turns an email into lower case and include the email in the report. Which line of the output changes for the first record?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does a validation rule return?
Answer
null when the value is fine, a message when it is not
The convention lets a validator collect messages from several rules instead of stopping at the first throw.
-
Why is a rule written as a function that returns a function?
Answer
So the length and the message are fixed once, and the rule is then called with a value
The factory configures the rule and the returned function is the rule itself, which is the higher-order pattern of this part.
-
What does this program print?
function required(msg = "required") { return (v) => (v ? null : msg); } console.log(required()(""));Answer
required
The empty string is falsy, so the rule returns the message it was configured with.
-
What does this program print?
function min(n) { return (v) => (v.length >= n ? null : "short"); } const errors = ["ab", "abcd"].map(min(3)).filter((e) => e !== null); console.log(errors.join(","));Answer
short
Only the two-letter value fails, and the filter keeps the one message while dropping the null.
-
Why does a validator return an array of messages instead of throwing?
Answer
A form can show every problem at once, and the caller decides what to do
A throw ends the walk, and a validator of user input usually wants to report all the fields that failed.
-
What does this program print?
function validate(rules, value) { return rules.map((rule) => rule(value)).filter((e) => e !== null); } console.log(validate([(v) => (v ? null : "empty"), () => null], "x").length);Answer
0
Both rules accept the value, so the filter drops the two nulls and the array is empty.
-
Where does the normalise step belong?
Answer
Before validation, as a pure step that returns a new record
One pure step keeps the rules simple and leaves the caller object unchanged, which the spread-based normaliser guarantees.
-
What does this program print?
const record = { name: "ada" }; function validate(r) { return r.name ? [] : ["name is required"]; } console.log(validate(record).length, record.name);Answer
0 ada
The validator reads the record and changes nothing, so there are no errors and the name is still there.
-
What does the
stopAtFirstoption do?Answer
It returns as soon as a rule fails
The loop leaves on the first message, which is what a quick check of a single input wants.
-
How are the counts at the end of the library program computed?
Answer
map to the error count, filter for zero and reduce for the total
The three array methods from the previous lessons give the list of counts, the number of valid records and the total in a few lines.
The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev