JavaScript Forms and Validation: Read Values, Validate and Submit
Forms are where users give an application data: sign-up, login, checkout, search and settings pages. They are also where most bugs hide, which is why testers spend so much time on boundary values, empty fields and invalid formats. In this lesson you will read every kind of form field with JavaScript, collect values with FormData, handle the submit event, use the browser’s built-in HTML5 validation and its JavaScript API (checkValidity, validity, setCustomValidity), and write custom validation with clear, accessible error messages. As in the previous lessons, every example ran in real Chrome and the browser filled in and submitted the forms like a user would.
📖 What You’ll Learn: accessing forms and fields, reading text inputs, checkboxes, radio buttons and selects, FormData and Object.fromEntries, the submit event and preventDefault, HTML5 validation attributes, the Constraint Validation API (checkValidity, reportValidity, validity, validationMessage), custom rules with setCustomValidity, novalidate and showing your own error messages, aria-invalid, and testing a validator with boundary values.
📝 Reading Form Fields
Every form field has a value property with its current content as a string. Checkboxes and radio buttons use checked; a select has value and selectedIndex. A form also gives access to its fields by name through form.elements:
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<form id="profile">
<input name="fullName" value="Asha Rao">
<input name="experience" type="number" value="4">
<label><input type="checkbox" name="newsletter" checked> Newsletter</label>
<label><input type="radio" name="level" value="junior"> Junior</label>
<label><input type="radio" name="level" value="senior" checked> Senior</label>
<select name="tool">
<option value="selenium">Selenium</option>
<option value="playwright" selected>Playwright</option>
</select>
</form>
<script src="app.js"></script>
</body>
</html>
📄 app.js
const form = document.querySelector("#profile");
const f = form.elements; // fields by name
console.log(f.fullName.value);
console.log(f.experience.value, typeof f.experience.value); // still a string
console.log(f.experience.valueAsNumber); // number inputs can give a number
console.log("newsletter:", f.newsletter.checked);
console.log("level:", form.querySelector('input[name="level"]:checked').value);
console.log("level (RadioNodeList):", f.level.value);
console.log("tool:", f.tool.value, "| index:", f.tool.selectedIndex, "| text:", f.tool.selectedOptions[0].text);
console.log(form.elements.length, "fields in the form");
🖥️ Browser console
Asha Rao
4 string
4
newsletter: true
level: senior
level (RadioNodeList): senior
tool: playwright | index: 1 | text: Playwright
6 fields in the form
| Field | Read | Set |
|---|---|---|
| Text, email, password, textarea | el.value | el.value = "x" |
| Number, range, date | el.value (string), valueAsNumber / valueAsDate | el.value |
| Checkbox | el.checked (boolean) | el.checked = true |
| Radio group | form.elements.name.value or :checked selector | radio.checked = true |
| Select | el.value, selectedIndex, selectedOptions | el.value = "x" |
| File input | el.files (FileList) | Not settable by script (security) |
📦 FormData and the submit Event
Listen for submit on the form, not click on the button: submit also fires when the user presses Enter in a field. Call preventDefault() to stop the page reload, then collect all named fields at once with FormData:
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<form id="contact">
<input name="name">
<input name="email" type="email">
<select name="topic"><option>Bug</option><option>Feature</option></select>
<label><input type="checkbox" name="urgent"> Urgent</label>
<button>Send</button>
</form>
<script src="app.js"></script>
</body>
</html>
📄 app.js
document.querySelector("#contact").addEventListener("submit", (event) => {
event.preventDefault();
const data = new FormData(event.currentTarget);
console.log(data.get("name"), data.get("topic"));
console.log("urgent:", data.get("urgent")); // unchecked boxes are left out
const payload = Object.fromEntries(data); // plain object, ready for JSON
console.log(JSON.stringify(payload));
// fetch("/api/contact", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(payload) });
});
🖥️ Browser console (after filling the form and pressing Enter)
Ravi Feature
urgent: null
{"name":"Ravi","email":"ravi@sqatools.in","topic":"Feature"}
- Only fields with a
nameattribute are included. - A checked checkbox without a
valueattribute gives"on"; an unchecked one is missing entirely (getreturnsnull). - For fields with several values (multi-select, checkbox groups) use
data.getAll("name"). - You can pass the
FormDataobject directly as afetchbody to sendmultipart/form-data, which file uploads require.
✅ Built-in HTML5 Validation
Browsers can validate forms with no JavaScript at all. Add attributes to the fields, and the browser blocks submission and shows a message until they are valid:
| Attribute | Rule |
|---|---|
required | Must not be empty |
type="email" / "url" / "number" | Must match the format |
minlength / maxlength | Text length limits |
min / max / step | Number and date limits |
pattern="[A-Z]{3}[0-9]{4}" | Must match a regular expression (whole value) |
The same rules are available to JavaScript through the Constraint Validation API. checkValidity() returns true or false; validity says which rule failed; validationMessage is the browser’s message:
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<form id="f">
<input id="email" type="email" required>
<input id="code" pattern="[A-Z]{3}[0-9]{4}" placeholder="ABC1234">
<input id="age" type="number" min="18" max="99">
</form>
<script src="app.js"></script>
</body>
</html>
📄 app.js
const email = document.querySelector("#email");
const code = document.querySelector("#code");
const age = document.querySelector("#age");
function report(input) {
const v = input.validity;
const failed = ["valueMissing", "typeMismatch", "patternMismatch", "rangeUnderflow", "rangeOverflow", "tooShort"].filter((k) => v[k]);
console.log(`#${input.id} "${input.value}" valid=${v.valid} ${failed.join(",")} ${input.validationMessage}`);
}
report(email); // empty but required
email.value = "not-an-email";
report(email);
email.value = "qa@sqatools.in";
report(email);
code.value = "abc1234";
report(code);
code.value = "ABC1234";
report(code);
age.value = "17";
report(age);
age.value = "120";
report(age);
console.log("form valid?", document.querySelector("#f").checkValidity());
🖥️ Browser console (Chrome, English)
#email "" valid=false valueMissing Please fill out this field.
#email "not-an-email" valid=false typeMismatch Please include an '@' in the email address. 'not-an-email' is missing an '@'.
#email "qa@sqatools.in" valid=true
#code "abc1234" valid=false patternMismatch Please match the requested format.
#code "ABC1234" valid=true
#age "17" valid=false rangeUnderflow Value must be greater than or equal to 18.
#age "120" valid=false rangeOverflow Value must be less than or equal to 99.
form valid? false
📌 Note: validationMessage text comes from the browser and the user’s language, so it differs between Chrome, Firefox and Safari. Test against the validity flags or your own messages rather than the exact browser wording.
⚠️ Watch out: Client-side validation is for user experience only. Anyone can bypass it (DevTools, disabling JavaScript, calling the API directly), so the server must validate everything again. A classic test: send invalid data straight to the API and check that it is rejected.
🛠️ Custom Rules with setCustomValidity
For rules HTML cannot express, such as “passwords must match” or “end date after start date”, call setCustomValidity(message). A non-empty message makes the field invalid; an empty string makes it valid again:
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<form id="reset">
<input id="pw" type="password" required minlength="8">
<input id="confirm" type="password" required>
<button>Reset password</button>
</form>
<script src="app.js"></script>
</body>
</html>
📄 app.js
const pw = document.querySelector("#pw");
const confirm = document.querySelector("#confirm");
function checkMatch() {
confirm.setCustomValidity(confirm.value === pw.value ? "" : "Passwords do not match");
}
pw.addEventListener("input", checkMatch);
confirm.addEventListener("input", checkMatch);
document.querySelector("#reset").addEventListener("submit", (e) => {
e.preventDefault();
console.log("submitted!");
});
document.querySelector("#reset").addEventListener("invalid", (e) => {
console.log(`blocked: #${e.target.id} -> ${e.target.validationMessage}`);
}, true); // invalid does not bubble, so listen in the capture phase
🖥️ Browser console (after a mismatched attempt, then a matching one)
blocked: #confirm -> Passwords do not match
submitted!
The first click was blocked by the browser (the invalid event fired and no submit happened); after fixing the confirmation, the form submitted.
💬 Showing Your Own Error Messages
Many apps add novalidate to the form to turn off the browser’s pop-up bubbles, keep the validation rules, and show their own messages next to each field. Set aria-invalid and link the message with aria-describedby so screen readers announce it (and so Playwright’s accessibility-based locators and assertions can find it):
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
<style>
.error { color: #b91c1c; font-size: 13px; }
[aria-invalid="true"] { border-color: #b91c1c; }
</style>
</head>
<body>
<form id="signup" novalidate>
<label for="email">Email</label>
<input id="email" name="email" type="email" required>
<label for="password">Password</label>
<input id="password" name="password" type="password" required minlength="8">
<label for="age">Age</label>
<input id="age" name="age" type="number" min="18" max="99">
<button>Create account</button>
</form>
<script src="app.js"></script>
</body>
</html>
📄 app.js
const form = document.querySelector("#signup");
const messages = {
valueMissing: (label) => `${label} is required.`,
typeMismatch: () => "Enter a valid email address, like name@example.com.",
tooShort: (label, el) => `${label} must be at least ${el.minLength} characters.`,
rangeUnderflow: (label, el) => `You must be at least ${el.min}.`,
rangeOverflow: (label, el) => `${label} must be ${el.max} or less.`,
};
function showError(input) {
const label = form.querySelector(`label[for="${input.id}"]`).textContent;
let error = document.getElementById(`${input.id}-error`);
if (!error) {
error = document.createElement("p");
error.id = `${input.id}-error`;
error.className = "error";
input.after(error);
input.setAttribute("aria-describedby", error.id);
}
const key = Object.keys(messages).find((k) => input.validity[k]);
error.textContent = key ? messages[key](label, input) : "";
input.setAttribute("aria-invalid", String(Boolean(key)));
return !key;
}
form.addEventListener("submit", (e) => {
e.preventDefault();
const results = [...form.querySelectorAll("input")].map(showError);
const errors = [...form.querySelectorAll(".error")].map((p) => p.textContent).filter(Boolean);
console.log(results.every(Boolean) ? "✓ account created" : `✗ ${errors.length} error(s): ${errors.join(" | ")}`);
});
🖥️ Browser console (after an invalid attempt, then a valid one)
✗ 3 error(s): Enter a valid email address, like name@example.com. | Password must be at least 8 characters. | You must be at least 18.
✓ account created
🧪 Tester Scenario: Boundary Value Tests for a Validator
Keep validation logic in a plain function so it can be tested with many inputs at once. Here a username rule (3–15 characters, letters, digits and underscore, must start with a letter) is checked against boundary and negative values, the same table you would write in a test plan:
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<input id="username">
<script src="app.js"></script>
</body>
</html>
📄 app.js
function validateUsername(name) {
if (name.trim() === "") return "required";
if (name.length < 3) return "too short";
if (name.length > 15) return "too long";
if (!/^[A-Za-z]/.test(name)) return "must start with a letter";
if (!/^[A-Za-z0-9_]+$/.test(name)) return "invalid characters";
return "ok";
}
const cases = [
["", "required"],
["ab", "too short"], // min - 1
["abc", "ok"], // min
["a".repeat(15), "ok"], // max
["a".repeat(16), "too long"], // max + 1
["1tester", "must start with a letter"],
["qa tester", "invalid characters"],
["qa_tester_01", "ok"],
["<script>", "must start with a letter"],
];
let failures = 0;
for (const [input, expected] of cases) {
const actual = validateUsername(input);
const ok = actual === expected;
if (!ok) failures++;
console.log(`${ok ? "✓" : "✗"} ${JSON.stringify(input).padEnd(20)} -> ${actual}`);
}
console.log(`${cases.length - failures}/${cases.length} passed`);
🖥️ Browser console
✓ "" -> required
✓ "ab" -> too short
✓ "abc" -> ok
✓ "aaaaaaaaaaaaaaa" -> ok
✓ "aaaaaaaaaaaaaaaa" -> too long
✓ "1tester" -> must start with a letter
✓ "qa tester" -> invalid characters
✓ "qa_tester_01" -> ok
✓ "<script>" -> must start with a letter
9/9 passed
The same table drives UI tests: for each row, fill the field, submit and assert the message, for example with a Playwright for loop that generates one test per row.
📝 Practice Questions with Answers
Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.
Q1. Read the values of a text input city and a checkbox remember when the form is submitted, without reloading the page.
Show answer
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<form id="f"><input name="city"><label><input type="checkbox" name="remember"> Remember</label><button>Go</button></form>
<script src="app.js"></script>
</body>
</html>📄 app.js
document.querySelector("#f").addEventListener("submit", (e) => {
e.preventDefault();
const { city, remember } = e.currentTarget.elements;
console.log(city.value, remember.checked);
});🖥️ Browser console
Pune trueQ2. Convert a form to a plain object with FormData and Object.fromEntries.
Show answer
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<form id="f"><input name="user" value="qa_lead"><input name="role" value="admin"></form>
<script src="app.js"></script>
</body>
</html>📄 app.js
const data = Object.fromEntries(new FormData(document.querySelector("#f")));
console.log(data);🖥️ Browser console
{"user":"qa_lead","role":"admin"}Q3. Make a phone field valid only for exactly 10 digits using an HTML attribute, and check it with checkValidity().
Show answer
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<input id="phone" pattern="[0-9]{10}" required>
<script src="app.js"></script>
</body>
</html>📄 app.js
const phone = document.querySelector("#phone");
for (const value of ["98765", "9876543210", "98765abcde"]) {
phone.value = value;
console.log(value, phone.checkValidity());
}🖥️ Browser console
98765 false
9876543210 true
98765abcde falseQ4. Show which validity flag fails for an email input containing “qa@”.
Show answer
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<input id="e" type="email">
<script src="app.js"></script>
</body>
</html>📄 app.js
const e = document.querySelector("#e");
e.value = "qa@";
console.log(e.validity.valid, e.validity.typeMismatch);🖥️ Browser console
false trueQ5. Use setCustomValidity so that a coupon field only accepts “SQA10” or “SQA20”.
Show answer
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<input id="coupon">
<script src="app.js"></script>
</body>
</html>📄 app.js
const coupon = document.querySelector("#coupon");
function check() {
coupon.setCustomValidity(["SQA10", "SQA20"].includes(coupon.value.toUpperCase()) ? "" : "Unknown coupon code");
}
for (const value of ["sqa10", "FREE100"]) {
coupon.value = value;
check();
console.log(value, coupon.checkValidity(), coupon.validationMessage);
}🖥️ Browser console
sqa10 true
FREE100 false Unknown coupon codeQ6. List five negative test values you would try on an “Age (18–60)” number field, and why.
Show answer
17 and 61 (just outside the boundaries), an empty value (required check), -5 or 0 (negative and zero), 18.5 (decimals when only whole years are allowed), and a very large number such as 99999999999 (overflow). Also try typing e, which number inputs accept as part of scientific notation, and pasting text. Then send the same values directly to the API to check server-side validation.
🧠 MCQ Quiz: Forms and Validation
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
- How do you read whether a checkbox is ticked?Answer: checkbox.checked. value is the string sent when it is checked.
- What type is
input.valuefor<input type="number">?Answer: string. Use valueAsNumber or Number() for a number. - Which event should you listen to for form submission?Answer: submit on the form. submit also fires when pressing Enter.
- Which fields does
new FormData(form)include?Answer: Fields with a name attribute (unchecked boxes excluded). No name, no entry. - What does
checkValidity()return?Answer: true or false. reportValidity() also shows the browser message. - Which validity flag is true for an empty required field?Answer: valueMissing. tooShort only applies to edited, non-empty values.
- How do you mark a field invalid with your own message?Answer: setCustomValidity(“message”). An empty string clears the error.
- What does the
novalidateattribute on a form do?Answer: Turns off the browser’s automatic validation on submit. The validity API still works for your own code. - Why must the server validate again?Answer: Client-side validation can be bypassed. Never trust the client.
- Which attribute links an error message to its input for screen readers?Answer: aria-describedby. Add aria-invalid=”true” as well.
💼 Interview Questions and Answers
Q1. How would you test a sign-up form?
Positive cases with valid data; required-field checks one field at a time; boundary values for lengths and numbers (min−1, min, max, max+1); invalid formats (email, phone, special characters, leading and trailing spaces); duplicate accounts; security inputs (HTML and script tags, SQL-like strings); accessibility of error messages; keyboard-only submission with Enter; and bypassing the UI to send invalid data straight to the API to verify server-side validation.
Q2. What is the difference between client-side and server-side validation?
Client-side validation (HTML attributes, JavaScript) gives instant feedback and saves round trips, but it runs on the user’s machine and can be bypassed. Server-side validation is the real protection for data integrity and security. Both are needed, and they should enforce the same rules; mismatches between them are a common source of bugs.
Q3. What is the Constraint Validation API?
The browser API behind HTML5 validation: checkValidity() and reportValidity() on fields and forms, the validity object with flags such as valueMissing and typeMismatch, validationMessage, the invalid event and setCustomValidity() for custom rules. It lets you reuse the browser’s rules while controlling how errors are shown.
Q4. Why might a Playwright test fill a field correctly but the form still says it is empty?
Usually the app validates on a different event (for example blur), or the test set the value in a way that fired no events (such as assigning value through evaluate). Use fill() or pressSequentially(), which fire real input events, and trigger blur by moving focus (press("Tab")) when the app validates on leaving a field.
❓ Frequently Asked Questions
🤔 Should I use the browser’s validation messages or my own?
Many apps use the HTML attributes for the rules but show their own messages with novalidate, because browser bubbles look different in every browser and cannot be styled.
🤔 How do I validate a field when the user leaves it?
Listen for the blur (or focusout) event and call your validation for that field. Validating on every input event can show errors before the user has finished typing.
🤔 Can JavaScript set the value of a file input?
No, for security reasons. Users must choose files themselves. Automation tools such as Playwright use setInputFiles(), which works through the browser’s automation interface.
🤔 Does pattern need ^ and $?
No. The pattern must match the whole value automatically, as if it were wrapped in ^(?:...)$.
🏁 Summary
- Read fields with
value(always a string),checkedfor checkboxes and radios, andform.elementsby name. - Handle
submiton the form, callpreventDefault(), and collect data withFormDataandObject.fromEntries. - HTML5 attributes (required, type, minlength, min/max, pattern) define rules;
checkValidity,validityandsetCustomValidityexpose them to JavaScript. - Show your own accessible messages with
novalidate,aria-invalidandaria-describedby. - Keep validators as testable functions, test boundaries and negatives, and always validate again on the server.
Next, continue with Lesson 60: localStorage and Cookies.
🎬 Watch JavaScript and automation tutorials on YouTube!
Subscribe to SqaToolsByDY • Practice on sqatools.in