Validate data contracts before domain operations
Quick answer
Input validation establishes that external data matches a defined contract. Syntax, structure, types, allowed values and business rules are distinct checks; return a clear rejection instead of silently coercing an invalid value.
How it works
At a JSON boundary, parse once, check a non-null object with expected own fields, then validate fields and cross-field constraints. Bound sizes before expensive work where possible. Do not use truthiness for numeric validity: zero can be legitimate. Client validation improves feedback; the server repeats authoritative checks. Validation alone is not context-specific output encoding or authorization.
Local examples
Run in Node.js v22.16.0 as a CommonJS script. Actual ByteMind editor support is unverified.
(async () => {const good=n=>Number.isInteger(n)&&n>=0&&n<=100;console.log(good(0),good("0"),good(101));})()Expected console output:
true false falseZero satisfies the explicit range; coercion and overflow do not.
Run in Node.js v22.16.0 as a CommonJS script. Actual ByteMind editor support is unverified.
(async () => {function valid(r,a){return [r,a].every(n=>Number.isInteger(n)&&n>=0&&n<=100)&&r<=a;}console.log(valid(0,0),valid(3,2),valid(3,3));})()Expected console output:
true false trueThe business relationship rejects an otherwise valid pair with insufficient stock.
Common mistakes
Do not let numeric strings or missing fields pass by implicit coercion. A valid JSON document is not necessarily a valid domain record.
Practice
Validate a shipment with integer requested and available quantities, requiring 0 ≤ requested ≤ available ≤ 100. Test zeros, equality, a string and a reversed inequality.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Validate data contracts before domain operations — Knowledge Check
Apply the concept and reason about local example output.
Which check is a semantic business rule for a shipment?
Why check Number.isInteger before comparing a JSON quantity?
Where must a server-side mutation repeat input validation?
What is the exact console output in Validate data contracts before domain operations example 1?
(async () => {const good=n=>Number.isInteger(n)&&n>=0&&n<=100;console.log(good(0),good("0"),good(101));})()What is the exact console output in Validate data contracts before domain operations example 2?
(async () => {function valid(r,a){return [r,a].every(n=>Number.isInteger(n)&&n>=0&&n<=100)&&r<=a;}console.log(valid(0,0),valid(3,2),valid(3,3));})()