Forms and Validation
Forms are how people give data to a web page: payment amounts, names, dates, choices. JavaScript's job is to read the values, validate them, show helpful errors, and submit the result without reloading the page. Modern browsers do much of this already: HTML attributes like required, type="email" and min validate on their own, and the Constraint Validation API lets JavaScript use and customize that built-in checking. Start with HTML, then add JavaScript where HTML can't express the rule. (This is the "HTML first" approach.)
In One Minute
- Listen for
submiton the form (notclickon the button), and callevent.preventDefault()to handle it in JavaScript. new FormData(form)reads every named field;Object.fromEntries(formData)turns it into a plain object.- HTML attributes validate for free:
required,type="email",min,max,minlength,pattern,step. form.checkValidity(),input.validity,input.setCustomValidity(message)andform.reportValidity()are the Constraint Validation API.inputfires on every change to a field's value;changefires when the change is committed (on blur, or immediately for checkboxes and selects).
Handling Submit
Listen to the form's submit event. It fires whether the person clicks the submit button or presses Enter in a field, which a button click listener would miss:
<form id="payment">
<label>Student <input name="student" value="Navika"></label>
<label>Amount <input id="amount" name="amount" type="number"></label>
<button>Record</button>
</form>
<script>
document.querySelector("#payment").addEventListener("submit", (event) => {
event.preventDefault();
const data = new FormData(event.currentTarget);
console.log(data.get("student"), data.get("amount"), typeof data.get("amount"));
});
</script>Navika 120 stringExplanation: pressing Enter in the amount field submitted the form. preventDefault() stopped the page from reloading. FormData read the fields by their name attribute; every value is a string, even from a type="number" input, so convert before calculating.
Reading Form Data
| Code | Gives |
|---|---|
new FormData(form) | All named fields |
formData.get("name") | One value (string, or a File for file inputs), null if missing |
formData.getAll("tags") | Every value for a name (checkbox groups, multi-selects) |
Object.fromEntries(formData) | A plain object (last value wins for repeated names) |
form.elements.amount | The field element itself |
input.value, input.valueAsNumber, checkbox.checked | A field's live value |
<form id="f">
<input name="name" value="Advitha">
<input name="grade" type="number" value="9">
<label><input type="checkbox" name="extras" value="bus" checked> Bus</label>
<label><input type="checkbox" name="extras" value="lunch" checked> Lunch</label>
<label><input type="checkbox" name="extras" value="sports"> Sports</label>
<select name="method"><option>card</option><option selected>check</option></select>
<button id="b">Save</button>
</form>
<script>
document.querySelector("#f").addEventListener("submit", (e) => {
e.preventDefault();
const data = new FormData(e.currentTarget);
console.log(JSON.stringify(Object.fromEntries(data)));
console.log(data.getAll("extras").join(", "));
console.log(e.currentTarget.elements.grade.valueAsNumber + 1);
});
</script>{"name":"Advitha","grade":"9","extras":"lunch","method":"check"}
bus, lunch
10Unchecked boxes aren't included at all, and Object.fromEntries keeps only the last value for a repeated name ("lunch"); use getAll for groups. valueAsNumber reads a number input as a real number.
Built-In Validation
HTML attributes describe the rules, and the browser enforces them before submit fires:
| Attribute | Rule |
|---|---|
required | Must not be empty |
type="email", type="url" | Must look like an email address or URL |
type="number" with min, max, step | Must be a number in range, on a step |
minlength, maxlength | Text length limits |
pattern="regex" | Must match the regular expression (the whole value) |
type="date" with min, max | Date range |
<form id="f">
<input id="email" name="email" type="email" required>
<input id="amount" name="amount" type="number" min="1" max="5000" step="0.01" required>
<button id="save">Save</button>
</form>
<script>
const form = document.querySelector("#f");
form.addEventListener("invalid", (e) => console.log("invalid:", e.target.name), true);
form.addEventListener("submit", (e) => {
e.preventDefault();
console.log("submitted", new FormData(form).get("email"));
});
</script>invalid: email
invalid: amount
submitted navika@example.comExplanation: the first click found both fields empty. The browser fired an invalid event for each, showed its own message on the first one, and didn't fire submit. After the fields were filled in, the second click submitted. The invalid event doesn't bubble, so the listener uses the capture phase (the true argument).
The Constraint Validation API
JavaScript can read and extend the browser's validation:
| Member | Description |
|---|---|
input.validity | An object of booleans: valueMissing, typeMismatch, rangeUnderflow, rangeOverflow, stepMismatch, tooShort, patternMismatch, customError, valid |
input.validationMessage | The browser's message for the current problem |
input.checkValidity() / form.checkValidity() | Returns true or false (fires invalid events) |
input.reportValidity() / form.reportValidity() | Same, and shows the messages |
input.setCustomValidity(message) | Marks the field invalid with your message; "" marks it valid again |
<input id="amount" type="number" min="1" max="5000" value="7500">
<input id="zip" pattern="\d{5}" value="7520">
<script>
const amount = document.querySelector("#amount");
const zip = document.querySelector("#zip");
console.log(amount.validity.rangeOverflow, amount.validity.valid);
console.log(zip.validity.patternMismatch);
zip.setCustomValidity("Enter a 5-digit US ZIP code.");
console.log(zip.validationMessage);
zip.setCustomValidity("");
zip.value = "75201";
console.log(zip.checkValidity());
</script>true false
true
Enter a 5-digit US ZIP code.
truesetCustomValidity is how you add rules HTML can't express, such as "the payment can't exceed the balance", while still using the browser's error display. Remember to clear it with "" when the value becomes valid, or the field stays invalid forever.
Custom Error Messages
For full control over how errors look, turn off the browser's popups with the novalidate attribute on the form, keep the validation rules, and show messages in the page yourself:
<form id="f" novalidate>
<label for="amount">Amount</label>
<input id="amount" name="amount" type="number" min="1" max="450" required aria-describedby="amount-error">
<p id="amount-error" role="alert"></p>
<button id="save">Save</button>
</form>
<script>
const form = document.querySelector("#f");
const amount = form.elements.amount;
const error = document.querySelector("#amount-error");
function messageFor(input) {
if (input.validity.valueMissing) return "Enter an amount.";
if (input.validity.rangeOverflow) return `The balance is only $${input.max}.`;
if (input.validity.rangeUnderflow) return "The amount must be at least $1.";
return "";
}
form.addEventListener("submit", (e) => {
e.preventDefault();
error.textContent = messageFor(amount);
amount.setAttribute("aria-invalid", String(!amount.validity.valid));
console.log(amount.validity.valid ? `Saved $${amount.value}` : `Error: ${error.textContent}`);
});
</script>Error: Enter an amount.
Error: The balance is only $450.
Saved $120The error paragraph is linked to the field with aria-describedby and announced by screen readers through role="alert"; aria-invalid marks the field's state for assistive technology.
input and change Events
| Event | Fires |
|---|---|
input | On every change of value: each keystroke, paste, autocomplete, voice input |
change | When a change is committed: on blur for text fields, immediately for checkboxes, radios and selects |
<input id="name"> <input id="other">
<p id="preview"></p>
<script>
const name = document.querySelector("#name");
name.addEventListener("input", () => {
document.querySelector("#preview").textContent = `Receipt for ${name.value}`;
});
name.addEventListener("change", () => console.log("change:", name.value, "|", document.querySelector("#preview").textContent));
</script>change: Navika | Receipt for NavikaUse input for live previews and clearing errors, and change for "save this field" actions.
In Practice
The Fee Tracker's payment form combines it all: HTML rules, one custom rule (the amount can't exceed the student's balance), messages on submit and cleared on input, and the data handed to a function as a typed object:
<form id="pay" novalidate data-balance="450">
<select name="student"><option>Navika</option><option>Srihitha</option></select>
<input id="amount" name="amount" type="number" min="1" step="0.01" required>
<span id="err" role="alert"></span>
<button id="save">Record payment</button>
</form>
<script>
const form = document.querySelector("#pay");
const amount = form.elements.amount;
const err = document.querySelector("#err");
function validate() {
const balance = Number(form.dataset.balance);
amount.setCustomValidity(amount.valueAsNumber > balance ? `Only $${balance} is due.` : "");
err.textContent = amount.validity.valid ? "" : amount.validationMessage;
return amount.validity.valid;
}
amount.addEventListener("input", () => { if (err.textContent) validate(); });
form.addEventListener("submit", (e) => {
e.preventDefault();
if (!validate()) return console.log("Blocked:", err.textContent);
const { student, amount: value } = Object.fromEntries(new FormData(form));
console.log(`Recorded $${Number(value).toFixed(2)} for ${student}`);
});
</script>Blocked: Only $450 is due.
Recorded $200.00 for NavikaCommon Mistakes
Listening to the button's click instead of the form's submit. Enter-key submissions are missed. Use submit.
Forgetting preventDefault(). The page reloads and your JavaScript never finishes.
Fields without name. FormData skips them.
Doing math on form values without converting. They are strings: use Number(...) or valueAsNumber.
Trusting client-side validation. Always validate on the server too.
Practice
Challenge: Build a form with a required email and a ZIP code that must be 5 digits. On submit, log either OK with both values or the name of the first invalid field.
Show solution
<form id="f" novalidate>
<input id="email" name="email" type="email" required>
<input id="zip" name="zip" pattern="\d{5}" required>
<button id="go">Sign up</button>
</form>
<script>
document.querySelector("#f").addEventListener("submit", (e) => {
e.preventDefault();
const form = e.currentTarget;
const firstInvalid = form.querySelector(":invalid");
if (firstInvalid) return console.log("Invalid:", firstInvalid.name);
const { email, zip } = Object.fromEntries(new FormData(form));
console.log("OK", email, zip);
});
</script>Invalid: zip
OK srihitha@example.com 94103Key Takeaways
| Task | Code |
|---|---|
| Handle submit | form.addEventListener("submit", (e) => { e.preventDefault(); ... }) |
| Read all fields | Object.fromEntries(new FormData(form)) |
| Is the form valid? | form.checkValidity() |
| Custom rule | input.setCustomValidity("message") / ("") |
| Live preview | input.addEventListener("input", ...) |
Was this tutorial helpful?