Sub topic 5
Building the sign-up form in HTML
This chapter builds the sign-up form that the rest of the tutorial improves. It assumes you know basic HTML and a little JavaScript, and that you know what an email service provider (ESP) does: it stores subscribers and sends campaigns. You do not need a backend framework. The chapter treats the server as an endpoint that accepts a POST request.
What the form must do
A sign-up form has four jobs:
- Collect a valid email address.
- Record that the person agreed to receive email.
- Reject obvious bot submissions.
- Send the data to your ESP or your own server.
HTML handles the first three at the browser level. The server still has to repeat those checks, because anyone can send a request without using your page.
The base form
<form action="https://example.com/subscribe" method="post">
<label for="email">Email address</label>
<input type="email" id="email" name="email" autocomplete="email" required>
<div style="position:absolute;left:-9999px" aria-hidden="true">
<label for="website">Leave this field empty</label>
<input type="text" id="website" name="website" tabindex="-1" autocomplete="off">
</div>
<label>
<input type="checkbox" name="consent" value="yes" required>
I agree to receive the weekly newsletter and can unsubscribe at any time.
</label>
<button type="submit">Subscribe</button>
</form>Without JavaScript, the browser submits this form as a full page load. That makes it a good baseline: it works even if your scripts fail to load.
The form element
action is the URL that receives the data. method="post" sends the fields in the request body. Never use get for sign-ups, because the email address would appear in the URL, browser history, and server logs.
If you omit enctype, the browser sends application/x-www-form-urlencoded. Most ESP endpoints accept this. Only use multipart/form-data when the endpoint documentation asks for it.
The email field
Each attribute on the email input has a purpose:
| Attribute | Effect |
|---|---|
| `type="email"` | Shows an email keyboard on phones and runs built-in format validation |
| `id` and `for` | Link the label to the input, so tapping the label focuses the field |
| `name="email"` | The key your server receives. Fields without a `name` are not submitted |
| `autocomplete="email"` | Lets the browser fill in the saved address |
| `required` | Blocks submission while the field is empty |
Two gotchas come up often. First, type="email" is lenient. The browser accepts a@b because it has no dot-free-domain rule, so a passing check does not mean the address exists. Second, a placeholder is not a label. Placeholder text disappears when the visitor types and has weak support in assistive technology. Always use a real label.
The consent checkbox
The checkbox is not pre-ticked. Under rules such as the GDPR, consent must come from a clear action by the visitor, and a pre-ticked box does not count. The label states what the person is signing up for and that they can leave. The chapter on consent covers the legal detail. Here, the point is the markup: the input sits inside its label, so clicking the text toggles the box, and no for attribute is needed.
required on the checkbox stops the form until the box is ticked. That suits a form whose only purpose is the newsletter. If the form also offers something else, such as a download, keep the newsletter checkbox optional and separate.
The honeypot field
The website field is a trap. Real visitors never see it. Simple bots fill every field they find, so a non-empty value tells the server to discard the submission. Several details matter:
- Hide it by moving it off-screen. Some bots skip fields hidden with
display:none, which defeats the trap. tabindex="-1"andautocomplete="off"stop keyboard users and browser autofill from filling it by accident.- Give it a believable name such as
website, nothoneypot. aria-hidden="true"keeps screen readers from announcing it. Some accessibility checkers flagaria-hiddenon a container that holds a focusable element. Thetabindex="-1"removes it from the tab order, but you should test with a screen reader.
The honeypot only stops unsophisticated bots. The spam chapter covers stronger layers.
Submitting without a page reload
A full page reload loses the visitor's place. You can enhance the form with fetch while keeping the plain HTML behavior as a fallback. Add a status area to the form:
<p id="form-status" role="status"></p>Then add this script:
const form = document.querySelector('form[action$="/subscribe"]');
const statusEl = document.querySelector('#form-status');
form.addEventListener('submit', async (event) => {
event.preventDefault();
statusEl.textContent = 'Sending...';
try {
const response = await fetch(form.action, {
method: 'POST',
body: new URLSearchParams(new FormData(form)),
headers: { Accept: 'application/json' }
});
if (response.ok) {
form.reset();
statusEl.textContent = 'Thanks! Check your inbox to confirm your address.';
} else {
statusEl.textContent = 'That did not work. Please check the address and try again.';
}
} catch (error) {
statusEl.textContent = 'Network problem. Please try again in a moment.';
}
});Three decisions here are worth understanding:
new URLSearchParams(new FormData(form))produces the same encoding as the plain HTML form. Passing theFormDataobject directly would sendmultipart/form-data, which some endpoints reject.- The built-in validation still runs. The browser checks
requiredandtype="email"before it fires thesubmitevent, so the handler only runs on a valid form. role="status"makes screen readers announce the message when its text changes. A visitor who cannot see the screen still learns the result.
Cross-origin requests also need the endpoint to allow your site through CORS headers. If the request fails in the browser but works in a command-line tool, CORS is the likely cause. Check your ESP's documentation, or fall back to the plain form post.
Checking the data on the server
Client checks improve the experience. They are not security, because a script can post anything to your endpoint. The server should repeat each check:
| Check | Why |
|---|---|
| Honeypot field is empty | Discards simple bot posts |
| `consent` equals `yes` | Keeps a record that the visitor agreed |
| Address matches a basic pattern and is under 254 characters | Rejects malformed input |
| Address is not already subscribed | Avoids duplicates and repeated confirmation emails |
This Python function shows the logic using only the standard library:
import re
EMAIL_PATTERN = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
def validate_signup(data):
"""Return (ok, reason) for a submitted form dictionary."""
if data.get("website", "").strip():
return False, "honeypot filled"
if data.get("consent") != "yes":
return False, "consent missing"
email = data.get("email", "").strip().lower()
if len(email) > 254 or not EMAIL_PATTERN.match(email):
return False, "invalid email"
return True, "ok"
print(validate_signup({"email": "[email protected]", "consent": "yes", "website": ""}))
print(validate_signup({"email": "[email protected]", "consent": "yes", "website": "http://spam"}))The first call prints (True, 'ok') and the second prints (False, 'honeypot filled'). When a bot trips the honeypot, many sites still return a success response. The bot then has no signal to adapt to.
Do not try to write a perfect email regular expression. The pattern above only catches obvious mistakes. The reliable way to prove an address works is to send a message to it, which is what double opt-in does, as a later chapter explains.
The request flow
Common errors
- Missing
nameattribute. The field shows on screen but the server never receives it. This is the most common reason a form "does nothing". - Label not linked to the input. Clicking the label does nothing, and screen readers announce an unnamed field. Match
fortoidexactly. - Duplicate
idvalues. If you place the same form in a page body and in a pop-up, two elements may shareid="email". Labels then point at the wrong input. Give each copy a unique id, such aspopup-email. - Button outside the form. A
buttonoutside theformelement does not submit it unless it uses theformattribute. - Disabling the submit button on load. If a script error leaves it disabled, nobody can subscribe. Keep the button enabled and rely on
required. - Posting over HTTP. Always use an
https://action. Browsers warn about insecure form posts.
Reusing the form in a pop-up
The same fields work inside a native dialog element. Only the wrapper changes, and the form inside is built exactly as above. A later chapter covers the pop-up's triggers and accessibility. For now, remember two rules: use unique ids in each copy of the form, and keep the server checks identical, because the endpoint cannot tell which copy was used.
Exercise
A teammate's form shows an email field and a Subscribe button, but the server logs show every request arriving with no address. The input is <input type="email" id="email" required>. What is wrong, and how would you also make the server resilient to this kind of mistake?
Show answer
The input has no name attribute, so the browser leaves it out of the submitted data. Add name="email". To make the server resilient, validate that email is present and return a clear error such as "invalid email" instead of failing silently, and log the rejection reason so the problem shows up quickly.
Exercise
Why does the fetch example send new URLSearchParams(new FormData(form)) instead of new FormData(form) directly, and what would you check if the request still failed only in the browser?
Show answer
Sending FormData directly uses multipart/form-data, while a plain HTML form uses application/x-www-form-urlencoded. Wrapping it in URLSearchParams keeps the encoding the same as the plain form, which many endpoints expect. If the request still fails only in the browser, check CORS: the endpoint must send headers that allow your site's origin.