All subjects · Information Technology · WIT12 3 hour practical exam on web development with HTML, CSS and JavaScript

Validating form data with JavaScript

Edexcel IAL Information Technology · WIT12 3 hour practical exam on web development with HTML, CSS and JavaScript

JavaScript validation checks form data in the browser and shows helpful messages before anything is sent. A 20-mark exam question usually includes validation of names, ages and codes, with messages (spec 9.2.2, 9.3.2, 9.3.3 and 7.3.4).

Practise this in the app: instant marking and a fix for every mistake. Free, no email needed to start.

Practise this lesson

Validation checks

CheckQuestion it asksJavaScript
PresenceHas something been entered?`value === ""` or `value.trim().length === 0`
LengthIs it the right number of characters?`value.length < 3`
RangeIs the number between the limits?`age >= 16 && age <= 99`
TypeIs it a number?`isNaN(Number(value))`
FormatDoes it match a pattern?`/^[A-Z]{2}[0-9]{3}$/.test(code)`
LookupIs it one of the allowed values?`["S", "M", "L"].includes(size)`

Validation checks that data is sensible and in the right format; it cannot check that it is true

A complete validation function

function validate() {
  const name = document.getElementById("name").value.trim();
  const age = Number(document.getElementById("age").value);
  const postcode = document.getElementById("postcode").value.toUpperCase();
  let message = "";
  if (name === "") {
    message += "Name is required. ";
  } else if (name.length < 3) {
    message += "Name must be at least 3 characters. ";
  }
  if (isNaN(age) || age < 16 || age > 99) {
    message += "Age must be from 16 to 99. ";
  }
  if (!/^[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}$/.test(postcode)) {
    message += "Postcode is not valid. ";
  }
  if (message === "") {
    message = "Thank you, " + name + ", you are registered.";
  }
  document.getElementById("message").textContent = message.trim();
  return message;
}

Good practice shown here: read each value into a variable once; convert numbers with Number(); collect all the error messages so the user can fix everything at once; display the message (Pearson's 2025 report noted messages stored in a variable but never shown); comment and indent the code.

Testing it

NameAgePostcodeMessage displayed
Sam Lee17LS1 4APThank you, Sam Lee, you are registered.
Jo17LS1 4APName must be at least 3 characters.
Priya15LS1 4APAge must be from 16 to 99.
(empty)abc12345Name is required. Age must be from 16 to 99. Postcode is not valid.

Results from running the function above

Connecting it to the form

document.getElementById("regForm").addEventListener("submit", function (event) {
  const result = validate();
  if (!result.startsWith("Thank you")) {
    event.preventDefault();      // stop the form being sent
  }
});

Validate on submit for the final check (preventDefault stops the form being sent), and optionally on blur or input to give feedback field by field. Test with normal, boundary (16 and 99) and erroneous data.

Worked example

Write the condition for an age that must be a whole number from 16 to 99, stored in the variable age (already converted with Number).

  1. Range: age >= 16 && age <= 99. Using > 16 would wrongly reject 16; Pearson's 2025 report noted ranges such as '> 18 and < 100' that did not match the requirement.
  2. Whole number: Number.isInteger(age).

Answer: `if (Number.isInteger(age) && age >= 16 && age <= 99) { ... }`

Key idea: Presence, length, range, type, format (regex) and lookup checks. Read values into variables, convert numbers, collect messages and display them, use preventDefault on submit when data is invalid, and test with normal, boundary and erroneous data.

Check yourself

  1. The validate function from this lesson runs with name Ana Diaz, age 14 and postcode SW19 5HX. What does the message paragraph show? ```js function validate() { const name = document.getElementById("name").value.trim(); const age = Number(document.getElementById("age").value); const postcode = document.getElementById("postcode").value.toUpperCase(); let message = ""; if (name === "") { message += "Name is required. "; } else if (name.length < 3) { message += "Name must be at least 3 characters. "; } if (isNaN(age) || age < 16 || age > 99) { message += "Age must be from 16 to 99. "; } if (!/^[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}$/.test(postcode)) { message += "Postcode is not valid. "; } if (message === "") { message = "Thank you, " + name + ", you are registered."; } document.getElementById("message").textContent = message.trim(); return message; } validate(); ```
    Show answer

    Age must be from 16 to 99.. Only the age fails (it is below 16), so the paragraph shows Age must be from 16 to 99..

  2. An age must be from 18 to 65 inclusive. Which set of test data checks the boundaries?
    • 20, 30 and 40
    • 17, 18, 65 and 66
    • abc and -5
    • 0 and 1000
    Show answer

    17, 18, 65 and 66. Boundary data is at and just beyond each limit.

  3. The code should display Required when the box is empty. Which condition completes it? ```html <input id="town" value=""> ``` ```js const v = document.getElementById("town").value; if (__________) { console.log("Required"); } else { console.log("OK"); } ```
    • `v === " "`
    • `v.length > 0`
    • `v == null`
    • `v === ""`
    Show answer

    `v === ""`. An empty text box has the value "" (an empty string), so v === "" is the presence check.

  4. What does event.preventDefault() do in a form's submit handler?
    • Stops the form being sent so the user can correct the data
    • Clears every field in the form
    • Sends the form twice
    • Removes the submit button
    Show answer

    Stops the form being sent so the user can correct the data. It cancels the browser's default action for the event, which for submit is sending the form.

  5. What is displayed when this code runs? ```js const pw = "sun2026"; if (pw.length < 8) { console.log("Too short by " + (8 - pw.length)); } else { console.log("OK"); } ```
    Show answer

    Too short by 1. The password has 7 characters, so Too short by 1.

  6. Why can validation not guarantee that data is correct?
    • It checks that data is reasonable and in the right format, not that it is true
    • Validation only works on numbers
    • Browsers ignore validation
    • It always rejects correct data
    Show answer

    It checks that data is reasonable and in the right format, not that it is true. An age of 30 passes a 16 to 99 range check even if the person is 40. Checking accuracy needs verification.

  7. Pearson's examiners reported that many candidates stored error messages in a variable but lost marks. What had they not done?
    Show answer

    They had not displayed the message to the user on the page, for example by setting the textContent of an element.. The message must reach the user: set an element's textContent or innerHTML, or use alert.

Practise with instant feedback

Sources

Last updated 8 November 2026. Spotted a mistake? Tell us.