JavaScript Validation Contracts and Defensive Inputs
Quick answer
A failure contract states what inputs are accepted, what a successful call returns and how invalid inputs are reported. Check type and range before performing calculations.
How it works
For a count, require a Number safe integer in a stated inclusive range. Reject numeric-looking strings unless conversion is explicitly part of the contract. A validation function can return a Boolean, a result object or throw a documented error; choose the form that callers expect. Local input validation does not replace server-side authorization or validation.
function valid(n) { return Number.isSafeInteger(n) && n >= 0 && n <= 10; }console.log(valid(0), valid(10), valid("5"));Expected output in Node.js:
true true falseBoth endpoints pass; the string fails the noncoercive predicate.
function units(n) { if (!Number.isSafeInteger(n) || n < 0 || n > 10) return {ok:false}; return {ok:true, value:n * 2}; }console.log(JSON.stringify(units(4)), JSON.stringify(units(11)));Expected output in Node.js:
{"ok":true,"value":8} {"ok":false}Valid input yields a typed result; invalid input produces the stated failure object.
Common mistakes
Do not silently coerce an empty string into zero for a strict numeric contract. Test boundary values and the wrong type.
Practice
Test both inclusive endpoints, a fractional Number, a string and a value above the limit.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Validation Contracts and Defensive Inputs — Knowledge Check
Apply the taught concept and predict the output.
Which check avoids coercion when validating a safe integer Number?
What should an inclusive upper bound of 10 accept?
What must a caller know before recovering from an invalid input?
What is the exact console output in JavaScript Validation Contracts and Defensive Inputs example 1?
function valid(n) { return Number.isSafeInteger(n) && n >= 0 && n <= 10; }console.log(valid(0), valid(10), valid("5"));What is the exact console output in JavaScript Validation Contracts and Defensive Inputs example 2?
function units(n) { if (!Number.isSafeInteger(n) || n < 0 || n > 10) return {ok:false}; return {ok:true, value:n * 2}; }console.log(JSON.stringify(units(4)), JSON.stringify(units(11)));