🚧 Under construction — VoTechWorks is being built. A free tech program — complimentary, as our commitment to get America working.
voTechWorksGrade 13 · a vocational technology learning center, by urbanicity
newSchoolWorks.com › VoTechWorks › Technology & Design › Web & Software Development › HTML, CSS, and JavaScript for Web Development › Lesson 10
TEC-WEB46-02 · Lesson 10 · 14 clock hours · lab

Forms, Validation, and Fetch API Basics

Objective. Students capture form input with JavaScript, perform client-side validation with user-facing error messages, and use the Fetch API with async/await to retrieve and display JSON data from a public REST endpoint.

⚠ Pending professional review

This lesson, its worked examples and its practice questions has not yet been verified by an industry-certified professional or by a certification or approval body. It is a study draft and may contain errors. Do not use it as instructions for work on a job site or on live equipment. Always follow your instructor, your supervising professional, and current official references and regulations.

VoTechWorks program approval and accreditation are still in progress. Credentials are issued only by the certifying bodies named in each program, after their own exams.

Forms, Validation, and Fetch API Basics

Web applications rely on forms to collect user data and on APIs to exchange it. This lesson covers three tightly linked skills: capturing form input with JavaScript, validating that input on the client side before submission, and using the Fetch API to retrieve live JSON data from a remote server.

HTML Forms and JavaScript Input Capture

A form element groups input controls — text boxes, email fields, checkboxes, and more. When a user clicks a submit button, the browser normally sends a request and reloads the page. To validate and handle input without a reload, attach an event listener to the form's `submit` event and call `event.preventDefault()` immediately inside the handler. This stops the default navigation and hands control to your script.

Read each field's current value through `document.getElementById('fieldId').value.trim()`. Trimming removes accidental leading or trailing spaces before you test the value.

Client-Side Validation

Validation checks that user input meets your requirements before it travels anywhere. Common checks include:

Display error messages next to the offending field, not in a browser alert. A typical pattern is to place an empty `<span>` with a unique `id` beside each input and write to its `textContent` when validation fails. Clear all spans at the top of the handler before re-running checks so stale messages do not persist.

Return from the handler without submitting if any check fails. Only proceed — for example, by calling `fetch()` — when every field is valid.

The Fetch API and async/await

`fetch()` is a built-in browser function that sends HTTP requests and returns a Promise. A Promise represents a value that will be available later. The `async/await` syntax lets you write asynchronous code that reads like synchronous code.

Declare a function with the `async` keyword. Inside it, use `await` before `fetch()` to pause execution until the response arrives, then `await response.json()` to parse the body:

```javascript

async function loadData() {

const statusEl = document.getElementById('status');

statusEl.textContent = 'Loading...';

try {

const response = await fetch('https://jsonplaceholder.typicode.com/users');

if (!response.ok) {

throw new Error(`HTTP error: ${response.status}`);

}

const users = await response.json();

statusEl.textContent = '';

renderCards(users);

} catch (error) {

statusEl.textContent = 'Failed to load data. Check your connection.';

console.error(error);

}

}

```

The `try/catch` block is mandatory. Network failures, DNS errors, and server errors do not automatically surface to the user — your `catch` block must display a readable message.

A loading state — text or a spinner shown before the data arrives — prevents a blank screen and reassures the user that work is in progress. Set it before `fetch()` and clear it after rendering.

Rendering JSON as HTML Cards

After parsing JSON into a JavaScript array, iterate with `forEach` or `map` and build DOM nodes:

```javascript

function renderCards(users) {

const container = document.getElementById('card-container');

container.innerHTML = '';

users.forEach(user => {

const card = document.createElement('div');

card.className = 'card';

card.textContent = user.name;

container.appendChild(card);

});

}

```

Avoid setting `innerHTML` with raw server or API strings directly — that is an XSS risk covered below.

Security Awareness: Why Client-Side Validation Is Never Enough

Client-side validation improves user experience — it gives fast feedback. It does not provide security. A malicious user can open browser DevTools, disable your JavaScript, and submit raw HTTP requests directly to your server, bypassing every check you wrote.

Cross-Site Scripting (XSS) is an attack where an adversary injects script tags or event-handler attributes into input fields. If your server stores that input and later renders it as raw HTML, the script runs in every subsequent visitor's browser. The defense is server-side output encoding and input sanitization — always, without exception.

Never concatenate unvalidated user input into `innerHTML`. Use `textContent` for plain text, or a trusted sanitization library when HTML is genuinely needed.

Key rule: validate on the client for UX, validate on the server for security. Both layers must exist independently.

Using Chrome DevTools Network Panel

Open DevTools (F12), select the Network tab, and trigger your `fetch()` call. You will see the request, its status code, response headers, and the raw JSON body. This is the primary tool for debugging API calls — check it before assuming your JavaScript is wrong.

Key terms9

event.preventDefault()A method called on a browser event object that cancels the event's default behavior — for a form submit event, it stops the page from reloading so JavaScript can handle input instead.
Client-side validationInput checking performed by JavaScript running in the user's browser before data is sent to a server; improves user experience but cannot be relied upon for security.
Regular expression (regex)A pattern written in a special syntax used to test whether a string matches a defined format, such as a valid email address or phone number.
PromiseA JavaScript object representing the eventual completion or failure of an asynchronous operation; returned by fetch() and resolved with await.
async/awaitJavaScript syntax that lets you write asynchronous code in a sequential style; async declares an asynchronous function, and await pauses execution until a Promise resolves.
Fetch APIA built-in browser interface for making HTTP requests; fetch() returns a Promise that resolves to a Response object whose body can be parsed as JSON or text.
Cross-Site Scripting (XSS)A security vulnerability where an attacker injects malicious scripts into content served to other users, typically by inserting script tags into input that is later rendered as raw HTML.
Loading stateA visual indicator — such as a text message or spinner — displayed while an asynchronous operation is in progress, preventing a blank screen and signaling activity to the user.
REST endpointA URL on a server that accepts HTTP requests and returns structured data, typically JSON, following REST (Representational State Transfer) conventions.
In class: Client-side validation lab: students add JavaScript validation to a multi-field registration form — checking required fields, email format with a regex pattern, and password minimum length — displaying error messages next to the relevant fields without page reload. · Fetch API exercise: students use fetch() with async/await to call a public API (such as JSONPlaceholder or Open-Notify) and dynamically render the returned JSON data as HTML cards inserted into the DOM, including a loading state and a catch block for network errors. · Security awareness discussion: instructor-led 20-minute session on why client-side validation is never a substitute for server-side validation, covering basic XSS injection concepts using a controlled demo in a sandboxed browser tab; students write a one-paragraph takeaway.
Materials: VS Code, Live Server, Chrome DevTools Network panel, MDN Fetch API reference, MDN Regular Expressions guide, JSONPlaceholder (jsonplaceholder.typicode.com) or another public API, provided starter form HTML
Check: Validation lab: instructor attempts to submit the form with seven invalid input combinations; all seven must produce the correct inline error message; Fetch lab: API data renders correctly with visible loading state; pass mark both components functional.

Practice check8

Answer each question, then check it. Nothing is recorded; this is your own practice.

CompTIA ITF+ — Software and Application Concepts
1. A student calls `event.preventDefault()` inside a form's submit handler. What is the primary effect?
PCEP Python — Basics of Python (regex concepts apply cross-language)
2. Which of the following regex patterns correctly tests whether a string contains at least one non-whitespace character, an @ symbol, another non-whitespace segment, a dot, and a final non-whitespace segment — a basic email format check?
CompTIA ITF+ — Networking Concepts
3. A fetch() call returns a Response object with `response.ok` equal to `false` and a status of 404. What does this indicate?
CompTIA Linux+ — Security
4. Why must server-side validation always be implemented even when thorough client-side validation is already in place?
CompTIA ITF+ — Security Concepts
5. A student writes `container.innerHTML = userData;` where `userData` comes directly from an API response. Which security risk does this introduce?
CompTIA ITF+ — Software and Application Concepts
6. In an async function, what happens if a `catch` block is omitted and the `fetch()` call encounters a network failure?
CompTIA ITF+ — IT Concepts and Terminology
7. Which Chrome DevTools panel is most useful for inspecting the HTTP status code and raw JSON body returned by a fetch() call?
PCEP Python — Control Flow (early return logic applies cross-language)
8. A form validation function runs all checks but never calls `return` after detecting an invalid field. What is the likely consequence?
Record this lesson on my transcript. Sign in with your key and enrollment email to record lessons (enroll free if you have no key). This page stays open to read and practise.