Skip to content
Aabha AI Academy
Skip to reading

JavaScript · Module 7

Check practice forms without sending data

Make the promise clear first

Our form is a local practice demonstration. It does not reserve a place, contact an organizer or store a person's details. Use the supplied invented name and an address at example.com. The screen must say this before anyone types. A success message should say “Practice check passed,” not “You are registered.” Honest interface wording is part of correctness.

Start with HTML labels, required attributes, email input type and a clear submit button. JavaScript should add a specific rule when the browser's built-in constraints are insufficient. Client-side validation helps a person correct input. It is not a security boundary: a real service must validate again on its server because browser code and requests can be changed.

Use the form's submission event

Listen on the form's submit event, not just the button's click. Submission can also happen through the keyboard. For the practice demo, call event.preventDefault() to stop normal navigation. This does not “validate” anything; it prevents the browser's default action for that event. We still need explicit checks.

form.addEventListener("submit", function (event) {
  event.preventDefault();
  updateNameRule();
  if (!form.reportValidity()) {
    return;
  }
  result.textContent = "Practice check passed. Nothing was sent.";
});
form.noValidate = true;

In the provided example, JavaScript sets form.noValidate = true only after attaching the submit handler. That disables automatic pre-submit validation so our handler can consistently update custom rules and call reportValidity itself. Ordinary automatic validation can prevent submit from firing when a field is invalid; controlling this sequence lets the handler refresh the custom rule first. HTML constraints still exist. reportValidity() evaluates them, returns a boolean and asks the browser to present validation feedback. Without JavaScript, the markup retains its default HTML validation and goes only to a local practice-result page. Fields deliberately have no name attributes, so their values are not included in a native form submission.

Add one custom rule and clear it correctly

A required text field containing spaces may not satisfy the human intention of “enter a name.” Trim the value to check that intention. Do not use a restrictive “letters only” pattern; names across languages contain many legitimate characters.

function updateNameRule() {
  const emptyAfterTrimming = nameInput.value.trim() === "";
  nameInput.setCustomValidity(
    emptyAfterTrimming ? "Enter a fictional practice name." : ""
  );
}
nameInput.addEventListener("input", updateNameRule);

The question-mark expression chooses one of two values: condition true gives the message, otherwise it gives the empty string. It is a compact alternative to an if/else assignment. A nonempty custom-validity message keeps a field invalid even if other constraints pass. The empty string clears that custom error. If you forget to clear it while the user corrects input, the form can remain stuck invalid.

For teaching clarity, our example also updates a visible text hint near the name input and connects it with aria-describedby. Invalid feedback should explain a correction and should not rely on color alone. Native validation bubbles and screen-reader announcements differ between browsers, so test the actual combination before production use.

Parse quantities intentionally

A number input's .value is still a string. You can use .valueAsNumber for a numeric result, which may be NaN when no number is available. For the practice party size, HTML sets min 1, max 4 and step 1. This isolated lesson checks the fixed 1–4 range. If a form combines quantity with event capacity, also reject a quantity above event.places: three people cannot fit into two available places. Our capstone checks interest in one event without collecting a party size. A later real application would check whole-number and capacity rules on the server too. Do not silently round 1.5 people to 2; that changes what the person entered.

Our event-interest demo uses a selected event ID. Before showing a result, find that ID in the currently loaded event collection. If it is missing or the event has zero places, explain the problem and do not display success. HTML options are not proof that a value is trustworthy; even a local developer can change them. This check is a useful habit even though no real submission exists.

Walk through failure before success

Run version 07 — download the course ZIP (Extract it and follow the included setup instructions for examples/07/index.html.). Submit empty fields. Then try a whitespace-only practice name, an invalid email shape and party size 0. Correct each field and submit a valid synthetic example such as name “Demo Visitor,” email “demo@example.com,” quantity 2. Open the Network panel: a successful practice check should not send a form request. The confirmation text is created locally.

Never test this with a real person's details. The program does not store the fields, but typing them into an arbitrary live website is already a disclosure. Keep exercises on your own local page. Our later localStorage example will save only non-sensitive event IDs, never names or email addresses.

References: client-side validation, reportValidity. The fallback and synthetic-data choices are course design decisions.

Practice and next step

Open exercise 07. Attempt the prediction before running code. Record the observed result and explain any mismatch. The explained solution is separate so you can choose when to look.

Read the separate answers and explanations

Reading progress

10 lessons remain open to guests. Marking a lesson read records reading only; it does not award assessment credit or a certificate.

Device reading marks require browser storage. Reading is always available.

Sign in or create an account to save separate account progress. Your current page is kept.