Contact Form Validation
handleFormSubmit blocks the default submission with event.preventDefault() and then runs validateContactForm().
| Field | Check |
|---|---|
| Name / Message | Whether it's empty |
Checks the format with the regex /^[^\s@]+@[^\s@]+\.[^\s@]+$/ |
For each field that fails, setFieldError displays an error message. It also changes the aria-invalid and aria-describedby attributes so that screen reader users, who have the screen read aloud to them, can also tell which field is wrong and why.
When Validation Passes: Actually Sending with Formspree
If validation passes, sendToFormspree() sends the form contents as a POST request to Formspree (an external service that emails form contents to you). The address is written in the <form>'s data-formspree-endpoint attribute.
const sendToFormspree = async (formData) => {
const endpoint = selectors.contactForm.dataset.formspreeEndpoint;
const response = await fetch(endpoint, {
method: 'POST',
headers: { Accept: 'application/json' },
body: formData,
});
if (!response.ok) {
throw new Error('Failed to send. Please try again in a moment.');
}
};| Part | Meaning |
|---|---|
method: 'POST' | A request that sends new data (a message) to the server |
body: formData | Sends the form fields as they are, packed into FormData |
Accept: application/json | Asks for the response as JSON instead of an HTML page (to get just the result without navigating away) |
if (!response.ok) | Throws an error manually if the status code is not 200-299 |
The last line is important. fetch() does not throw an error and finishes normally even when the server returns 400 or 500, so if you don't check the status code yourself, a "success" message might appear even when sending failed. For details, see "fetch does not throw on 404 or 500" in the GitHub API Integration article.
While sending, setSubmitting(true) blocks the button with disabled and changes its text to "Sending...". This prevents the same message from being sent twice, and the finally block releases the button again whether it succeeded or failed.
Why Browser Validation Alone Is Not Enough
validateContactForm() is validation for the user's convenience. It tells you right away about wrongly filled fields without a round trip to the server, so it's fast and friendly, but it is not a security measure.
- JS running in the browser can be turned off or modified by the user with the developer tools.
- Someone can also skip the browser entirely and send a request straight to the submission address with a tool like
curl.
[User] ──▶ [Browser check] ──▶ [Server check] ──▶ Save / send email
(convenience) (security)
[curl, etc.] ─────────────────▶ [Server check] ← skips the browser checkAs an analogy, browser validation is the greeter at the store entrance, and server validation is the guard in front of the safe. Even with a greeter, you can't do without the guard. In this project, Formspree plays the server's role, so spam filtering and required-field checks on the receiving side are left to Formspree's settings. If you build your own server, you must check the same rules once more on the server.
Be Careful When Showing Input Back on the Screen
When putting values the user entered back on the screen, use textContent instead of innerHTML. If someone enters HTML or a script snippet in the name field, innerHTML may interpret it as real code and run it. This kind of attack is called XSS (Cross-Site Scripting).
// Dangerous: the input is interpreted as HTML
statusEl.innerHTML = `${name}, your message has been sent`;
// Safe: the input is displayed as plain text
statusEl.textContent = `${name}, your message has been sent`;This project builds everything on screen, from error messages and success messages to project cards, with textContent and createElement, and never uses innerHTML. The code comments even say "does not use innerHTML (prevents XSS)." XSS is covered in detail together with CSRF, another form-related attack, in the CSRF and XSS article.
What's Missing
- Currently validation runs only at submission time; real-time validation while typing (e.g. checking with the
blurevent when leaving a field) is not implemented. - On a send failure, the same message is shown regardless of the status code. Splitting 4xx (input problem) and 5xx (server problem) into "Please check your input" and "Please try again in a moment" would make it clearer what the user should do.
Summary
- On submit, the browser checks name, email and message, and shows errors and accessibility attributes on the wrong fields
- If it passes,
fetchsends a POST to Formspree, and failures are checked manually withresponse.ok - The button is blocked while sending to prevent duplicate submissions
- Browser validation is a convenience feature; security checks are the job of the receiving side (the server, here Formspree)
- Only
textContentis used when putting text on the screen, to prevent XSS
Source: Codyssey-B1/B1-1
