JavaScript / Basic: values and browser foundations / Lesson 7
From form text to a validated calculation
Trace an input from text through explicit validation to a small calculation, with clear handling for rejected values.
On this page
Lesson goals
- Separate text parsing from domain validation.
- Represent invalid input without calculating a misleading total.
- Test boundaries and preserve the original input.
- Validate complete quantity text and safe integer arithmetic at separate boundaries.
- Render actionable error and success states without treating a valid zero as failure.
Define the boundary
A form control provides text, even when the user intends a quantity. Choose a contract before conversion: this example accepts a nonempty whole number greater than zero and prices expressed in nonnegative integer cents. The calculation receives numbers, while the interface owns the original text and any message shown to the user. This separation makes it possible to test the calculation without a browser and change the interface without silently changing its arithmetic.
Convert and inspect
Trimming removes surrounding whitespace, but conversion alone does not establish validity: Number converts an empty string to zero and invalid numeric text to NaN. Check for empty text separately, then use Number.isInteger and the domain condition. The example prints the converted quantity only if all checks pass. It keeps text unchanged, which lets a form report the actual input and ask for a correction instead of presenting a fabricated total.
const text = " 3 ";
const quantity = Number(text.trim());
const valid = text.trim() !== "" && Number.isInteger(quantity) && quantity > 0;
console.log(valid ? quantity : "invalid quantity");
The empty-text check is independent of numeric conversion; all three conditions must hold.
Keep calculation independent
A small function can enforce its own numeric preconditions even if an interface has already checked them. This matters when a second caller bypasses the form. Returning null here is an explicit rejection convention; a real application should document that convention and avoid confusing it with a valid zero total. The unit price can be zero, but the quantity cannot. Larger applications may need safe-integer and overflow checks before multiplication.
function totalCents(quantity, unitCents) {
if (!Number.isInteger(quantity) || quantity < 1) return null;
if (!Number.isInteger(unitCents) || unitCents < 0) return null;
return quantity * unitCents;
}
console.log(totalCents(3, 250));
console.log(totalCents(0, 250));
The function accepts validated integers and uses null to signal a rejected contract.
Choose a useful error path
Report which field needs correction without revealing private data in logs. For an empty quantity, show that a quantity is required; for a non-integer or nonpositive number, describe the allowed range. Do not turn every invalid input into zero, because that makes a failed validation look like a successful free order. If input is reused later, validate it at that new trust boundary too, rather than assuming the earlier screen cannot be bypassed.
Verify boundaries and ownership
Test empty and whitespace-only text, a positive integer, zero, a negative value, a fraction, and nonnumeric text. Check that the original text remains available and that invalid input never reaches the success display. Test a free item separately: a zero unit price produces zero for a valid quantity, while a zero quantity is rejected. Predict each result before running the code, then explain any discrepancy from the conversion and validation rules.
Define each boundary and its units
A form starts with text supplied by a user, even when that text represents a number. A calculation should instead receive values that satisfy a documented contract. For this lesson, quantity must be a positive safe integer and unit price must be a nonnegative safe integer in cents. The result is also required to be a safe integer. Zero price is valid; an empty quantity is not. State these choices explicitly because another application might allow zero quantity or use a different monetary representation.
Separate the process into reading text, validating and converting it, calculating, and rendering a result or an error. The browser adapter owns the controls and messages. A pure calculation function can receive validated numbers and return a total without reading a document. This makes it possible to test arithmetic independently from the page and avoids mixing display strings with numeric values. If data is sent to a server, the server must validate it again according to its own contract.
Validate representation before conversion
Trim surrounding whitespace, reject an empty string, and decide which numeric syntax the application accepts. Number accepts formats beyond plain decimal digits, including scientific notation, so require a digit-only string first if the form promises whole decimal digits. Convert only after that representation check. Then use Number.isSafeInteger and a positive range check: a very long digit string can convert to an unsafe integer even though every character is a digit. Do not use parseInt as a complete-input validator, because it can accept a valid prefix of malformed text such as 3x.
The unit price needs its own validation. A finite number can still be negative, fractional, or outside the safe integer range. Require an integer number of cents and check its allowed bounds. Do not use a truthiness test for price, because zero is a valid free item in this contract. The parser should return a distinct success or error result so the caller never needs to guess whether zero represents an error.
Guard the multiplication result
Two safe integer operands can have a product outside the safe integer range. Check the product with Number.isSafeInteger before treating it as an exact cent total, or establish bounds that guarantee a safe product. JavaScript Number uses floating-point representation; displaying a rounded value does not restore exactness once precision has been lost. When larger exact amounts are required, choose a different documented representation and conversion policy rather than silently accepting an unsafe result.
Keep units consistent. Multiplying a count by cents per item yields cents; converting that result to a currency display is a separate formatting concern. A valid quantity of three and a unit price of 250 cents yields 750 cents. A valid quantity of two and a price of zero yields zero, not an error. Test the pure calculation with ordinary values, zero price, and a product that exceeds the safe range. Use synthetic values and never treat client-side arithmetic as an authoritative financial record.
Make invalid input actionable
An invalid quantity should not reach the calculator. Preserve the user's text so it can be corrected, show a concise message explaining the required format or range, and associate that message with the input. On a later valid submission clear or update the prior error and display the new total. Do not leave a stale success total visible as if it belonged to invalid input; choose a clear state policy and test it. A message such as "Enter a positive whole number" is more useful than a generic failure notice.
Listen for the form submit event so keyboard submission and button activation use the same path. If handling the form locally, prevent its default navigation when appropriate, then read and validate the current values. Keep native labels and controls. Error text and an invalid state should be available beyond color alone. These browser behaviors require a real browser to verify, while the standalone numerical examples below can be checked independently in Node.
Test decisions and ownership
Construct a table before implementation: ordinary quantity " 3 " with price 250 should give 750; empty text should be rejected; quantity "2" with price zero should give zero. Add zero quantity, a negative sign, fractional text, malformed suffix, a very large digit string, and the boundary of the permitted range. If leading zeroes are allowed by the digit-only policy, include a case such as "003" and explain that conversion yields three. If the product has a maximum quantity, test it and the next value.
Assert the returned status and exact numeric total, not merely that a click handler ran. Confirm that invalid input produces no total and leaves the text available for correction. Check that a successful retry replaces the error and that price zero remains valid. The form adapter should own page updates while the calculator owns only its value contract. Test them separately, then verify their integration using a synthetic form in a browser; do not log real customer entries to diagnose a parsing rule.
20 worked examples
1. Trim a valid quantity
Problem: Convert a quantity surrounded by spaces before calculating a synthetic total.
- Trimming removes the surrounding spaces and leaves the digit 3.
- The positive safe integer passes the parser and is returned as numeric three.
function parse(text) { if (typeof text !== "string") return null; const s = text.trim(); if (!/^\d+$/.test(s)) return null; const n = Number(s); return Number.isSafeInteger(n) && n > 0 ? n : null; }
console.log(parse(" 3 "));
3
Why this result follows: The positive safe integer passes the parser and is returned as numeric three.
2. Reject empty text
Problem: Reject an empty quantity before it can become numeric zero.
- The digit-only check does not match an empty string.
- The parser returns its invalid sentinel without accepting Number empty-text conversion to zero.
function parse(text) { if (typeof text !== "string") return null; const s = text.trim(); if (!/^\d+$/.test(s)) return null; const n = Number(s); return Number.isSafeInteger(n) && n > 0 ? n : null; }
console.log(parse(""));
null
Why this result follows: The parser returns its invalid sentinel without accepting Number empty-text conversion to zero.
3. Reject whitespace only
Problem: Reject quantity text containing only spaces and no digits.
- Trimming turns this input into an empty string.
- The digit-only condition rejects the empty result before numeric conversion is attempted.
function parse(text) { if (typeof text !== "string") return null; const s = text.trim(); if (!/^\d+$/.test(s)) return null; const n = Number(s); return Number.isSafeInteger(n) && n > 0 ? n : null; }
console.log(parse(" "));
null
Why this result follows: The digit-only condition rejects the empty result before numeric conversion is attempted.
4. Accept leading zeroes
Problem: Interpret leading zeroes under the stated digit-only quantity policy.
- All three characters are decimal digits and the text is nonempty.
- Number converts the accepted digit representation to the positive safe integer three for this quantity.
function parse(text) { if (typeof text !== "string") return null; const s = text.trim(); if (!/^\d+$/.test(s)) return null; const n = Number(s); return Number.isSafeInteger(n) && n > 0 ? n : null; }
console.log(parse("003"));
3
Why this result follows: Number converts the accepted digit representation to the positive safe integer three for this quantity.
5. Reject a suffix
Problem: Reject a seat count containing digits followed by an alphabetic suffix.
- The full trimmed string fails the digits-only condition.
- The parser rejects the whole malformed input instead of accepting a numeric prefix.
function parse(text) { if (typeof text !== "string") return null; const s = text.trim(); if (!/^\d+$/.test(s)) return null; const n = Number(s); return Number.isSafeInteger(n) && n > 0 ? n : null; }
console.log(parse("3x"));
null
Why this result follows: The parser rejects the whole malformed input instead of accepting a numeric prefix.
6. Reject a decimal point
Problem: Reject fractional quantity text when whole decimal digits are required.
- The decimal point does not satisfy the digit-only representation.
- The input is rejected before it can be used as a fractional item count.
function parse(text) { if (typeof text !== "string") return null; const s = text.trim(); if (!/^\d+$/.test(s)) return null; const n = Number(s); return Number.isSafeInteger(n) && n > 0 ? n : null; }
console.log(parse("2.5"));
null
Why this result follows: The input is rejected before it can be used as a fractional item count.
7. Reject a negative sign
Problem: Reject negative quantity text under the positive-integer form contract.
- The minus sign is not one of the allowed digit characters.
- The representation fails before conversion, so a negative quantity cannot reach the calculation.
function parse(text) { if (typeof text !== "string") return null; const s = text.trim(); if (!/^\d+$/.test(s)) return null; const n = Number(s); return Number.isSafeInteger(n) && n > 0 ? n : null; }
console.log(parse("-2"));
null
Why this result follows: The representation fails before conversion, so a negative quantity cannot reach the calculation.
8. Reject zero quantity
Problem: Distinguish a numeric-looking zero quantity from a permitted positive quantity.
- The text passes the digit check and converts to numeric zero.
- The separate greater-than-zero domain check rejects zero even though its representation is valid.
function parse(text) { if (typeof text !== "string") return null; const s = text.trim(); if (!/^\d+$/.test(s)) return null; const n = Number(s); return Number.isSafeInteger(n) && n > 0 ? n : null; }
console.log(parse("0"));
null
Why this result follows: The separate greater-than-zero domain check rejects zero even though its representation is valid.
9. Reject scientific notation
Problem: Reject exponential text even though Number could convert this notation.
- The letter e makes the full text fail the digit-only policy.
- The stated form grammar is narrower than every numeric format accepted by Number.
function parse(text) { if (typeof text !== "string") return null; const s = text.trim(); if (!/^\d+$/.test(s)) return null; const n = Number(s); return Number.isSafeInteger(n) && n > 0 ? n : null; }
console.log(parse("1e2"));
null
Why this result follows: The stated form grammar is narrower than every numeric format accepted by Number.
10. Reject unsafe digits
Problem: Reject a digit-only quantity outside the safe integer range.
- The representation contains digits but converts beyond the safe integer limit.
- The safe-integer check rejects the numeric result even after the syntax check succeeds.
function parse(text) { if (typeof text !== "string") return null; const s = text.trim(); if (!/^\d+$/.test(s)) return null; const n = Number(s); return Number.isSafeInteger(n) && n > 0 ? n : null; }
console.log(parse("9007199254740992"));
null
Why this result follows: The safe-integer check rejects the numeric result even after the syntax check succeeds.
11. Calculate an ordinary total
Problem: Multiply three validated items by 250 cents per item.
- Both operands meet their integer and sign requirements.
- Multiplying the count by cents per item yields an exact total of 750 cents.
function total(q, cents) { if (!Number.isSafeInteger(q) || q <= 0 || !Number.isSafeInteger(cents) || cents < 0) return null; const n = q * cents; return Number.isSafeInteger(n) ? n : null; }
console.log(total(3, 250));
750
Why this result follows: Multiplying the count by cents per item yields an exact total of 750 cents.
12. Keep zero price
Problem: Calculate the total for two items whose unit price is zero.
- Zero is an allowed nonnegative safe integer price.
- The valid product is zero cents and must not be mistaken for an error sentinel.
function total(q, cents) { if (!Number.isSafeInteger(q) || q <= 0 || !Number.isSafeInteger(cents) || cents < 0) return null; const n = q * cents; return Number.isSafeInteger(n) ? n : null; }
console.log(total(2, 0));
0
Why this result follows: The valid product is zero cents and must not be mistaken for an error sentinel.
13. Reject negative price
Problem: Reject an otherwise valid quantity with a negative unit price.
- The quantity is positive but the price fails the nonnegative check.
- The calculation returns the invalid sentinel before multiplying a price that violates the stated contract.
function total(q, cents) { if (!Number.isSafeInteger(q) || q <= 0 || !Number.isSafeInteger(cents) || cents < 0) return null; const n = q * cents; return Number.isSafeInteger(n) ? n : null; }
console.log(total(2, -1));
null
Why this result follows: The calculation returns the invalid sentinel before multiplying a price that violates the stated contract.
14. Reject fractional cents
Problem: Reject a unit price expressed as a fractional cent value.
- The price is nonnegative but is not a safe integer.
- The cents contract requires whole integer units, so the calculation rejects this price.
function total(q, cents) { if (!Number.isSafeInteger(q) || q <= 0 || !Number.isSafeInteger(cents) || cents < 0) return null; const n = q * cents; return Number.isSafeInteger(n) ? n : null; }
console.log(total(2, 1.5));
null
Why this result follows: The cents contract requires whole integer units, so the calculation rejects this price.
15. Reject numeric text at calculator
Problem: Reject a string passed directly to the numeric calculation boundary.
- Number.isSafeInteger does not coerce the string argument to a number.
- The adapter must parse quantity first; the calculator accepts only validated numeric values.
function total(q, cents) { if (!Number.isSafeInteger(q) || q <= 0 || !Number.isSafeInteger(cents) || cents < 0) return null; const n = q * cents; return Number.isSafeInteger(n) ? n : null; }
console.log(total("2", 100));
null
Why this result follows: The adapter must parse quantity first; the calculator accepts only validated numeric values.
16. Reject unsafe product
Problem: Reject a product outside safe integer precision despite safe operands.
- Both arguments are individually safe integers but their product is too large.
- The final safe-integer check prevents returning an inexact cent total as valid.
function total(q, cents) { if (!Number.isSafeInteger(q) || q <= 0 || !Number.isSafeInteger(cents) || cents < 0) return null; const n = q * cents; return Number.isSafeInteger(n) ? n : null; }
console.log(total(2, Number.MAX_SAFE_INTEGER));
null
Why this result follows: The final safe-integer check prevents returning an inexact cent total as valid.
17. Accept the safe limit
Problem: Calculate a total exactly at the maximum safe integer boundary.
- One times the maximum safe integer stays at that same boundary.
- The product satisfies Number.isSafeInteger and can be returned as the exact total.
function total(q, cents) { if (!Number.isSafeInteger(q) || q <= 0 || !Number.isSafeInteger(cents) || cents < 0) return null; const n = q * cents; return Number.isSafeInteger(n) ? n : null; }
console.log(total(1, Number.MAX_SAFE_INTEGER));
9007199254740991
Why this result follows: The product satisfies Number.isSafeInteger and can be returned as the exact total.
18. Reject null input
Problem: Reject a missing quantity represented by null instead of text.
- The parser checks the incoming type before calling trim.
- A non-string value takes the invalid path without throwing a missing-method error.
function parse(text) { if (typeof text !== "string") return null; const s = text.trim(); if (!/^\d+$/.test(s)) return null; const n = Number(s); return Number.isSafeInteger(n) && n > 0 ? n : null; }
console.log(parse(null));
null
Why this result follows: A non-string value takes the invalid path without throwing a missing-method error.
19. Separate parse and calculate
Problem: Parse a normal quantity and pass its number to the calculator.
- The parser produces numeric four and the caller checks its sentinel.
- The calculator receives valid numeric operands and returns 500 cents for four items.
function parse(text) { if (typeof text !== "string") return null; const s = text.trim(); if (!/^\d+$/.test(s)) return null; const n = Number(s); return Number.isSafeInteger(n) && n > 0 ? n : null; }
function total(q, cents) { if (!Number.isSafeInteger(q) || q <= 0 || !Number.isSafeInteger(cents) || cents < 0) return null; const n = q * cents; return Number.isSafeInteger(n) ? n : null; }
const q = parse("4"); console.log(q === null ? "invalid" : total(q, 125));
500
Why this result follows: The calculator receives valid numeric operands and returns 500 cents for four items.
20. Do not calculate invalid text
Problem: Skip the calculation when quantity parsing rejects malformed input.
- The full quantity string fails the digit-only parser and returns null.
- The conditional takes the error path rather than sending an invalid quantity to the calculator.
function parse(text) { if (typeof text !== "string") return null; const s = text.trim(); if (!/^\d+$/.test(s)) return null; const n = Number(s); return Number.isSafeInteger(n) && n > 0 ? n : null; }
function total(q, cents) { if (!Number.isSafeInteger(q) || q <= 0 || !Number.isSafeInteger(cents) || cents < 0) return null; const n = q * cents; return Number.isSafeInteger(n) ? n : null; }
const q = parse("4x"); console.log(q === null ? "invalid" : total(q, 125));
invalid
Why this result follows: The conditional takes the error path rather than sending an invalid quantity to the calculator.
Common errors and fixes
Empty text becomes a plausible zero
- Why it happens
- Number converts an empty string to zero.
- How to fix it
- Check trimmed text for emptiness before accepting the conversion.
- Prevent it next time
- Include whitespace-only input in boundary tests.
A fraction reaches an integer quantity calculation
- Why it happens
- A numeric conversion was mistaken for domain validation.
- How to fix it
- Require Number.isInteger and the allowed range.
- Prevent it next time
- State representation and domain constraints separately.
A rejected quantity is displayed as a free order
- Why it happens
- The caller treats null or a fallback zero as success.
- How to fix it
- Branch explicitly on the documented rejection value.
- Prevent it next time
- Test the invalid path and the valid zero-price path independently.
20 practice exercises
1. What happens for text " 3 " and unit price 250 cents?
Show hint
Trim and validate the whole quantity before multiplying.
Show worked solution
Trimming produces "3" and conversion produces integer 3. The value is positive, so the calculation returns 750 cents. The original text can remain in the control while the numeric value is passed to the calculation.
Trim " 3 " to "3", verify the positive safe integer contract, and convert it to numeric 3. Multiplying by 250 cents yields 750 cents. Preserve the original control text while passing the numeric value to the calculation.
Check your solution
- The numeric quantity is 3.
- The returned total is 750 cents.
2. Compare an empty quantity with quantity 2 and unit price 0.
Show hint
Distinguish a missing quantity from a valid zero price.
Show worked solution
The empty text is rejected before calculation. Quantity 2 and zero unit price meet the contract and produce a valid total of zero; treating both cases as the same would hide an input error.
Reject the empty quantity before conversion and do not calculate a total for it. For quantity 2 and unit price 0, both values satisfy their respective rules and produce a valid zero-cent total. A truthiness test must not confuse these outcomes.
Check your solution
- Empty quantity is rejected.
- Quantity 2 at zero cents succeeds with total 0.
3. Parse " 6 " under a positive digit-only quantity rule and calculate at 50 cents.
Show hint
Trim before validating the full text.
Show worked solution
Trimming gives "6", which contains only digits and converts to the safe positive integer 6. Multiplying by 50 cents gives 300 cents. Keep the original form text available while passing the validated number to the calculator.
Check your solution
- Parsed quantity is 6
- Total is 300 cents
4. Explain why empty quantity text must be rejected before calling Number on it.
Show hint
Inspect Number("") under this required-field policy.
Show worked solution
Number("") produces numeric zero, so conversion alone hides the missing entry. Trim the text and reject an empty result before conversion. Return an explicit invalid outcome and keep the field available for correction rather than calculating a zero quantity.
Check your solution
- Empty text is rejected
- No total is calculated
5. Determine whether "007" is accepted under the stated digit-only positive quantity policy.
Show hint
Leading zeroes are permitted by the stated policy.
Show worked solution
The text consists entirely of digits and converts to numeric 7, which is a positive safe integer. It is accepted under this specific policy. A different product may forbid leading zeroes, but that would require an explicit additional grammar rule.
Check your solution
- The parsed value is 7
- The stated policy accepts the representation
6. Determine whether "3x" may reserve three items under a whole-input digit policy.
Show hint
A numeric prefix is not the complete valid input.
Show worked solution
Reject the input because the letter violates the full digit-only grammar. parseInt may return 3 from a prefix, but that does not validate the whole value. Show a correction message and do not create a reservation or calculate a total.
Check your solution
- The input is rejected
- No reservation or total is produced
7. Explain why "1e2" is rejected even though Number("1e2") produces 100. Explain the decision.
Show hint
Compare the form grammar with the conversion function grammar.
Show worked solution
The stated form accepts decimal digit characters only, and the letter e violates that grammar. Number supports additional numeric notation, so successful conversion is insufficient. Reject the text before conversion unless the product deliberately changes its documented input policy.
Check your solution
- Number can produce 100
- The digit-only policy rejects the text
8. Check quantity "0" and unit price 100 under a strictly positive quantity rule.
Show hint
Separate syntax validity from the quantity range.
Show worked solution
The text passes a digits-only syntax check and converts to numeric zero, but it fails the positive quantity rule. Return an invalid quantity outcome and do not calculate a total. The unit price does not make the quantity valid.
Check your solution
- The syntax is valid
- The quantity is rejected as zero
9. Calculate a valid quantity of 5 with a zero-cent unit price. Explain the decision.
Show hint
Zero is allowed for price even though it is falsy.
Show worked solution
Both values satisfy the stated contracts: 5 is a positive safe integer and zero is a nonnegative safe integer price. The product is zero cents. Represent success separately from errors so the valid zero total is not mistaken for failure.
Check your solution
- The price is accepted
- The total is 0 cents
10. Reject a unit price of -10 cents while quantity 2 is valid.
Show hint
Validate price independently from quantity.
Show worked solution
Quantity 2 satisfies its positive integer rule, but -10 fails the nonnegative price rule. Return an invalid price outcome before multiplication. Do not silently replace the negative price with zero, because that changes the meaning of the submitted data.
Check your solution
- Quantity is valid
- The negative price is rejected
11. Determine whether a price of 2.5 cents satisfies the whole-cent contract. Explain the decision.
Show hint
A finite nonnegative number can still be fractional.
Show worked solution
Reject 2.5 because the price must be a safe integer number of cents. It is nonnegative and finite, but not an integer. If fractional cents are needed, establish a different unit and rounding policy rather than silently rounding this input.
Check your solution
- The price is nonnegative
- The whole-cent check rejects it
12. Check a digit string representing 9007199254740992 against the safe integer rule. Explain the decision.
Show hint
Valid characters do not guarantee safe numeric precision.
Show worked solution
The text passes a digit-only grammar but its numeric value is outside the safe integer range. Reject it using Number.isSafeInteger after conversion. This second check protects exact integer reasoning that a character-level validation cannot establish.
Check your solution
- The syntax passes
- The safe-integer check rejects the number
13. Explain why two safe operands can still produce an unsafe cent total.
Show hint
Check the product, not just each operand.
Show worked solution
Multiplying 2 by Number.MAX_SAFE_INTEGER produces a value outside the safe integer range even though each operand is safe. Check Number.isSafeInteger on the product and reject it, or impose bounds that guarantee the result is safe before multiplying.
Check your solution
- Both operands can be safe
- The unsafe product is rejected
14. Calculate quantity 1 at Number.MAX_SAFE_INTEGER cents and assess the product. Explain the decision.
Show hint
Multiplying by one preserves the safe boundary.
Show worked solution
The product is 9007199254740991 cents, equal to Number.MAX_SAFE_INTEGER. It remains a safe integer, so it passes the stated mathematical contract. A real product may impose a much smaller business limit separately from this language-level boundary.
Check your solution
- The product is 9007199254740991
- The result is safe at this boundary
15. Design a parser result that distinguishes invalid input from a valid zero price.
Show hint
Use an explicit status rather than a truthiness test.
Show worked solution
Return a result such as {ok: true, value: 0} for a valid zero price and {ok: false, error: "invalid"} for failure. The caller checks ok rather than testing value truthiness, so zero remains a legitimate successful value.
Check your solution
- Valid zero has ok true
- Invalid input has ok false
16. Describe the UI state after invalid input follows an earlier successful total of 500 cents.
Show hint
Avoid presenting the old total as the new result.
Show worked solution
Keep the current user input available, show an associated correction message, and clear or clearly invalidate the previous total according to the documented state policy. Do not calculate with invalid data. Test that the old 500 is not presented as the new result.
Check your solution
- The field remains editable
- The prior total is not presented as current
17. Describe a valid retry after a quantity error was displayed for an empty field.
Show hint
Update both the error and the success state.
Show worked solution
When the user supplies a valid quantity, validate again, clear or update the previous error association and invalid state, and render the new calculated total. For quantity 2 at 100 cents, the displayed result is 200 cents and the stale error is gone.
Check your solution
- The stale error is cleared
- The new total is 200 cents
18. Keep a calculator independent of browser controls while accepting quantity and cents.
Show hint
Pass validated values as parameters and return the result.
Show worked solution
Define a function taking numeric quantity and unit cents, checking the calculation contract and returning a total or explicit error. Let the form adapter read controls and render messages. Test the function directly without document, then test the browser integration separately.
Check your solution
- The calculator does not read document
- The adapter owns display updates
19. Plan tests for quantity boundaries, zero price, and an unsafe product. Explain the decision.
Show hint
Include valid, malformed, missing, and precision cases.
Show worked solution
Assert that "1" is accepted, "0" and blank text are rejected, and "3x" is rejected. Assert that quantity 2 at zero cents returns zero and that multiplying 2 by Number.MAX_SAFE_INTEGER is rejected. Check both outcome status and value.
Check your solution
- Minimum positive quantity is accepted
- Zero price succeeds and unsafe product fails
20. Explain why a server must validate submitted quantity again after client validation.
Show hint
A client request can arrive without using this form.
Show worked solution
Client validation improves immediate feedback but does not establish trust in a request. The server must independently validate the representation, range, price authority, and arithmetic according to its own rules. A caller can send a request that bypasses the browser form entirely.
Check your solution
- The server validates independently
- Client validation is not authorization
Key takeaways
- Parse text explicitly and validate the domain separately.
- Keep rejection distinct from a valid zero total.
- Conversion is not a substitute for checking input syntax and range.
- A safe product must be checked even when both operands are safe integers.
- Zero price is valid under this contract while an empty quantity is invalid.