smartyfy.mrindigi.com

Web Development Pro | Lesson 035 | Validate Data at the Boundary

Web Development Pro · Lesson 35 of 60

Module 4: Data, modules, and state

In this lesson

Prerequisites and learning outcomes

Complete lesson 34 first. This lesson builds on json syntax and application schemas. By the end, you can check remote records before rendering and report malformed data usefully. Plan 10–15 minutes for the core explanation and additional time for the worked practice.

Treat parsed data as untrusted input

A JSON file can parse successfully while containing the wrong shape. The directory expects a collection of workshop records, not a single object, a null value, or records with missing titles. Validate at the boundary before the renderer receives data. This gives the rest of the application a simpler, explicit contract.

Validation is not a claim that the information is true in the real world. A record can have a valid date format while describing an event that was canceled. This lesson checks structure and permitted values for fictional data. Provenance, freshness, authorization, and real-world verification are separate responsibilities.

Define the record contract

Each record requires a unique id containing lowercase letters, digits, and hyphens; a nonempty title up to one hundred UTF-16 code units after trimming; a category of repair or textiles; and an integer durationMinutes from one through 480. The id limit is forty ASCII characters. JavaScript string length counts UTF-16 code units, so an emoji may use two units rather than one visible character. The returned record contains only these known fields, giving downstream code a normalized representation.

File validate.mjs:

export function parseWorkshops(value) {
  if (!Array.isArray(value)) throw new Error('Expected a workshop array.');
  const ids = new Set();
  return value.map((record, index) => {
    const fail = message => { throw new Error(`Record ${index + 1}: ${message}`); };
    if (record === null || typeof record !== 'object' || Array.isArray(record)) fail('expected an object');
    if (typeof record.id !== 'string' || record.id.length > 40 || !/^[a-z0-9-]+$/.test(record.id)) fail('invalid id');
    if (ids.has(record.id)) fail('duplicate id');
    if (typeof record.title !== 'string' || record.title.trim() === '' || record.title.trim().length > 100) fail('invalid title');
    if (!['repair', 'textiles'].includes(record.category)) fail('invalid category');
    if (!Number.isInteger(record.durationMinutes) || record.durationMinutes < 1 || record.durationMinutes > 480) fail('invalid duration');
    ids.add(record.id);
    return { id: record.id, title: record.title.trim(), category: record.category, durationMinutes: record.durationMinutes };
  });
}

A Set tracks ids already encountered. The regular expression checks the id's allowed characters and requires at least one character. The small fail helper adds a record position to diagnostic messages without echoing the entire incoming record. Every helper used in this function is defined here or is a standard language API.

Normalize only what the contract permits

Trimming title whitespace is an intentional normalization. Automatically converting a duration string such as '60' to a number would be a different policy. This validator rejects it because the data contract requires a JSON number. Strict boundaries catch upstream mistakes early instead of letting several inconsistent representations spread through the application.

The function returns new record objects and a new array. It does not mutate the incoming records. Unknown fields are omitted from the returned shape, but that is not a guarantee that sensitive data was never downloaded. Data minimization should happen at the source too. Do not request private fields merely because the renderer will ignore them.

Rejecting the entire collection on one bad record is also a policy choice. It prevents a partially displayed schedule from appearing complete. Another system might deliberately display valid records and report skipped entries, but it would need a clear partial-data status and evidence about what was omitted. Silent dropping can hide important information.

Validate after parsing and before rendering

The supplied api.mjs fetches the local file, checks the HTTP response, parses JSON, and calls parseWorkshops. The entry module only renders after that sequence succeeds. Its failure message says the directory could not load valid data and invites checking the local source; developer diagnostics identify the failed contract.

Keep error messages useful without exposing private payloads or internal credentials. “Record 2: duplicate id” is actionable for a developer. Dumping the complete response into a public status region is unnecessary and can leak information. The visitor-facing message should explain the effect and next step in ordinary language.

Do not use validation as an excuse to insert fields through innerHTML. A title can legitimately contain angle brackets as plain text under this contract. The renderer still uses textContent. Structural validation and safe output are complementary protections, because different destinations interpret strings differently.

Choose boundary tests from each rule

For ids, test an empty string, uppercase letters, excessive length, and a duplicate. For titles, test whitespace, a missing value, and the allowed length boundary. For duration, test zero, a fraction, a numeric string, the upper limit, and one above it. For the top level, test an object and null instead of an array.

Include a valid empty array if “no records exist” is a legitimate successful state. The validator accepts it here. The renderer must distinguish that successful empty collection from a load error. A zero-length array is not automatically proof of a broken service.

Also assert that normalization returns the expected trimmed title and leaves the original input unchanged. A validator that silently edits shared source objects can create confusing side effects even while returning apparently correct data. Test both the accepted output and the rejected cases.

Understand the evidence boundary

The tests run the exact validation module against local values and controlled fetch responses. They inspect error messages, normalized fields, duplicate detection, and nonmutation. These are genuine runtime checks of the application contract. They do not establish the truth of fictional event information or the behavior of every possible external service.

The browser loading path remains a separate manual check because the authoring environment cannot run its browser/socket workflow. The complete example includes all data and module files, so you can serve it locally and inspect both a valid file and a deliberately broken disposable copy without contacting a third party.

Worked practice

Worked exercise 1: Reject a numeric string

Task: A record has durationMinutes: '60'. Worked answer: reject it under this contract rather than silently converting it. The source should provide the number 60. If conversion becomes a requirement, document it and add tests for empty, fractional, and malformed strings.

Worked exercise 2: Find duplicate identity

Task: Two otherwise valid records use id='bike-101'. Worked answer: reject the second occurrence with a duplicate-id diagnostic. A stable id must identify one record; accepting duplicates would make later selection and URL references ambiguous.

Worked exercise 3: Preserve literal content

Task: A valid title is “Repair <together>”. Worked answer: retain it as text and render with textContent. Validation does not need to ban every punctuation character merely to compensate for choosing an unsafe HTML-output method.

Knowledge check

Question 1

What does successful JSON parsing guarantee? A) Valid JSON syntax, not the application's full contract. B) Unique ids. C) Current event information. D) Allowed categories.

Check question 1: answer and explanation

Answer: A. Parsed values can still have an unsuitable shape or meaning.

Question 2

Why return new normalized objects? A) To make omission of unknown fields undo the original download. B) To provide a clear output shape without changing the input. C) To guarantee omitted sensitive fields were never transmitted. D) To make accepted title strings safe for HTML parsing.

Check question 2: answer and explanation

Answer: B. Normalization and ownership are explicit while privacy remains a separate concern.

Question 3

Why reject duplicate ids? A) Repeated titles are always forbidden. B) The JSON parser already requires all record values to be unique. C) Identity-based lookups would become ambiguous. D) JSON requires unique values everywhere.

Check question 3: answer and explanation

Answer: C. The application contract needs stable record identity, beyond JSON syntax rules.

Question 4

What does accepting an empty array mean here? A) The request failed before any data could be inspected. B) The top-level array check was bypassed. C) Every invalid record was silently removed. D) A valid successful collection may contain no records.

Check question 4: answer and explanation

Answer: D. Empty success and failure should remain distinct states.

Question 5

Does a validated title become safe for every output context? A) No; use context-appropriate rendering such as textContent. B) Yes, innerHTML is now always safe. C) Yes, validation turns text into trusted code. D) Yes, if the title is short.

Check question 5: answer and explanation

Answer: A. Structure checks do not replace safe handling at each destination.

Sources and further reading