Forms and validation with JavaScript
Read form fields, handle submit, validate input and show helpful messages that guide visitors.
In this lesson you will
- Read text, checkbox, radio and select values
- Handle the submit event
- Write simple validators
- Show clear error messages
About 19 minutes
Forms: where visitors talk to your page
Sign-up boxes, search bars, contact forms, checkout pages: forms are how people give your site information. JavaScript can read what they typed, check it before it goes anywhere, and answer instantly with friendly messages instead of making the visitor wait for a server to complain. This is called validation, and it is one of the most practical jobs in front-end development.
Reading form fields
const name = document.querySelector("#name");
const agree = document.querySelector("#agree");
const plan = document.querySelector("#plan");
console.log(name.value); // text typed
console.log(agree.checked); // true or false
console.log(plan.value); // selected option's value
Text inputs, textareas and selects use .value, which is always a string, even for type="number". Checkboxes and radio buttons use .checked.
Handling the submit event
const form = document.querySelector("#signup");
form.addEventListener("submit", (e) => {
e.preventDefault(); // stay on the page
const data = new FormData(form);
console.log(data.get("email"));
console.log(Object.fromEntries(data)); // all fields as an object
});
Fields must have a name attribute to appear in FormData. Object.fromEntries turns the data into a plain object you already know how to use.
Writing a validator
function validateEmail(value) {
const v = value.trim();
if (v === "") return "Email is required";
if (!v.includes("@") || !v.includes(".")) return "Enter a valid email";
return ""; // empty string means no error
}
function validatePassword(value) {
if (value.length < 8) return "At least 8 characters";
if (!/[0-9]/.test(value)) return "Include a number";
return "";
}
Notice the convention: each validator returns a message when something is wrong and an empty string when all is well. That makes them easy to combine and test. The odd-looking /[0-9]/ is a regular expression; .test() checks whether the text contains a digit. You will meet regular expressions properly in the advanced lessons.
Complete the sign-up form. On submit, show ‘Password too short’ if the password has fewer than 8 characters, otherwise ‘Welcome!’.
<style>
body{font-family:Arial;padding:16px;max-width:320px}
input,button{width:100%;padding:10px;margin:4px 0;box-sizing:border-box;font-size:15px}
button{background:#5A28C8;color:#fff;border:0;border-radius:8px;font-weight:700}
#msg{margin-top:8px;font-weight:700}
</style>
<form id="f">
<input id="pw" type="password" placeholder="Password">
<button>Sign up</button>
</form>
<div id="msg"></div>
<script>
const f = document.getElementById('f');
const msg = document.getElementById('msg');
f.addEventListener('submit', function (e) {
e.preventDefault();
// check the password length and set msg.textContent
});
</script>
const pw = document.getElementById(‘pw’).value; if (pw.length < 8) {…} else {…}
<style>
body{font-family:Arial;padding:16px;max-width:320px}
input,button{width:100%;padding:10px;margin:4px 0;box-sizing:border-box;font-size:15px}
button{background:#5A28C8;color:#fff;border:0;border-radius:8px;font-weight:700}
#msg{margin-top:8px;font-weight:700}
</style>
<form id="f">
<input id="pw" type="password" placeholder="Password">
<button>Sign up</button>
</form>
<div id="msg"></div>
<script>
const f = document.getElementById('f');
const msg = document.getElementById('msg');
f.addEventListener('submit', function (e) {
e.preventDefault();
const pw = document.getElementById('pw').value;
if (pw.length < 8) {
msg.textContent = 'Password too short';
msg.style.color = '#D63384';
} else {
msg.textContent = 'Welcome!';
msg.style.color = '#0E9F6E';
}
});
</script>
Good error messages
- Say what to do, not just what went wrong: “Use at least 8 characters” beats “Invalid”.
- Put the message next to the field, not in a pop-up.
- Do not shout. Calm text and a clear colour work better than all capitals.
- Do not rely on colour alone. Add words or an icon for people who cannot see red.
- Validate on submit, and also when leaving a field (the
blurevent) so errors appear in a helpful moment.
Using the browser’s own validation
<input type="email" required minlength="3">
<input type="number" min="1" max="10">
<input pattern="[0-9]{4}" title="Four digits">
const email = document.querySelector("#email");
console.log(email.validity.valid); // true or false
console.log(email.validationMessage); // browser's own message
email.setCustomValidity("Please use your work email");
email.reportValidity(); // show the message
The HTML attributes you learned in the HTML course do much of the work for free. JavaScript’s validity object lets you read the result and customise messages. Use both: HTML for the basics, JavaScript for special rules.
Live-check the username while typing: show ‘Too short’ under 4 characters, ‘No spaces allowed’ if it contains a space, otherwise ‘Looks good’.
<style>body{font-family:Arial;padding:16px} input{padding:10px;font-size:16px;width:90%} #m{margin-top:8px;font-weight:700}</style>
<input id="u" placeholder="Choose a username">
<div id="m"></div>
<script>
const u = document.getElementById('u');
const m = document.getElementById('m');
u.addEventListener('input', function () {
// check the value and show a message
});
</script>
Check u.value.length < 4, then u.value.includes(' '), then the good case.
<style>body{font-family:Arial;padding:16px} input{padding:10px;font-size:16px;width:90%} #m{margin-top:8px;font-weight:700}</style>
<input id="u" placeholder="Choose a username">
<div id="m"></div>
<script>
const u = document.getElementById('u');
const m = document.getElementById('m');
u.addEventListener('input', function () {
const v = u.value;
if (v.length < 4) { m.textContent = 'Too short'; m.style.color = '#D63384'; }
else if (v.includes(' ')) { m.textContent = 'No spaces allowed'; m.style.color = '#D63384'; }
else { m.textContent = 'Looks good'; m.style.color = '#0E9F6E'; }
});
</script>
Checkboxes, radios and selects
// radio group: find the chosen one
const chosen = document.querySelector('input[name="size"]:checked');
console.log(chosen ? chosen.value : "Nothing chosen");
// several checkboxes
const boxes = document.querySelectorAll('input[name="topping"]:checked');
const toppings = Array.from(boxes).map(b => b.value);
console.log(toppings);
// select element
const sel = document.querySelector("#country");
console.log(sel.value, sel.selectedIndex);
Trusting front-end validation as your only protection. JavaScript checks can be bypassed by anyone. They exist to help honest visitors. Always validate again on the server before saving anything important.
After a successful submit, call form.reset() to clear all fields, and move focus back to the first one with input.focus() for a smooth experience.
Worked example: a complete contact form check
Let us tie the pieces together in the shape you will use on real sites: several fields, one function per rule, errors shown beside each field, and the form accepted only when every field passes.
const rules = {
name: v => v.trim().length < 2 ? "Please enter your name" : "",
email: v => /^\S+@\S+\.\S+$/.test(v) ? "" : "Enter a valid email",
message: v => v.trim().length < 10 ? "Write at least 10 characters" : ""
};
form.addEventListener("submit", (e) => {
e.preventDefault();
let ok = true;
for (const field in rules) {
const input = form.elements[field];
const error = rules[field](input.value);
form.querySelector(`[data-error="${field}"]`).textContent = error;
if (error) ok = false;
}
if (ok) console.log("Send the message");
});
An object of rule functions is a neat idea: adding a field means adding one line. The loop walks through every rule, writes the message beside the field, and remembers if anything failed. Only when ok is still true do we proceed.
The pattern /^\S+@\S+\.\S+$/ is a regular expression for a rough email shape: some text, an at sign, some text, a dot, some text. It is deliberately simple. You will learn how to read these patterns in the advanced lessons.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What type is input.value for type="number"?
- Number
- Boolean
- String
- Object
Values are always strings.
How do you check whether a checkbox is ticked?
box.valuebox.selectedbox.onbox.checked
checked is true or false.
Why call e.preventDefault() in a submit handler?
- To submit twice
- To stop the page reloading
- To clear the form
- To hide the form
Otherwise the browser reloads the page.
What does new FormData(form) collect?
- Only the first field
- The page title
- All named fields of the form
- Cookies
It gathers every field that has a name.
Why validate again on the server?
- JavaScript checks can be bypassed
- Servers are faster
- It is optional always
- To save bandwidth
Front-end checks are a convenience, not security.
Summary
- Use value and checked to read fields.
- Handle submit and call preventDefault.
- Validators return a message or an empty string.
- Always re-validate on the server.
Questions
How do I validate an email properly?
Use type="email" plus a simple check. The only certain test is sending a confirmation email.
Why is my number a string?
Field values are strings. Convert with Number(value) before maths.
What does the name attribute do?
It labels the field in FormData and when submitting to a server.
