Form Validation and Autofill
What Is It?
Validation checks an answer before submission. Autofill helps the browser fill familiar details such as a name or email.
What the Tags Mean
required: an answer is needed.minandmax: allowed numeric range.minlengthandmaxlength: text length.autocomplete: names the kind of personal detail.
Example 1
Save each example as index.html and open it in your browser. Each code block is a complete page.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Validation and Autofill</title>
</head>
<body>
<form>
<label for="email">Email (required)</label>
<input id="email" name="email" type="email" required autocomplete="email">
<button type="submit">Check</button>
</form>
<pre id="result" role="status">Your answers will appear here. Nothing is sent or saved.</pre>
<script>
document.querySelectorAll("form").forEach((form) => {
form.addEventListener("submit", (event) => {
event.preventDefault();
const answers = [];
for (const [name, value] of new FormData(form)) {
answers.push(name + ": " + (value instanceof File ? value.name : value));
}
document.getElementById("result").textContent = answers.join("\n") || "No answers entered.";
});
});
document.querySelectorAll("button[type=button]").forEach((button) => {
button.addEventListener("click", () => {
button.closest("form").requestSubmit();
});
});
</script>
</body>
</html>Browser preview
What you see: Submitting an empty or badly formatted email shows a browser message. A valid answer appears below the form.
Example 2: Another Use
Limit a booking to between one and four seats.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Validation and Autofill</title>
</head>
<body>
<label for="seats">Seats: 1 to 4</label>
<input id="seats" name="seats" type="number" min="1" max="4">
</body>
</html>Browser preview
Simple Tip
Browser checks help readers. A real server must check the answers again before trusting them.
Try It Yourself
Try an empty email, an invalid email, and a valid email.