Forms without a framework
A form already does most of the work: it knows its fields, it validates them and it sends them. This lesson reads a form through form.elements, checks it with the browser's own validation, and sends it with fetch, without a framework or a single extra library.
In this lesson
- checkRead every field at once with new FormData(form)
- checkLet required, type and pattern do the checking
- checkShow your own message with setCustomValidity()
- checkSend the form with fetch and keep the page in place
Last lesson the weather card talked to an API with fetch. Most apps also take something in, so let's build a form properly.
Start with the markup. A form, a label for every field, and a button of type submit. Before any JavaScript, this already works: press Enter and the browser sends it.
Now listen for submit on the form itself, not click on the button. That way Enter, the button and a screen reader's submit all arrive in one place.
new FormData(form) gives you every named field in one go. Turn it into a plain object with Object.fromEntries and you have exactly what the server expects.
For checking, lean on the browser first. required, type="email" and pattern cover most forms, and form.checkValidity() tells you whether all of them pass.
When you need your own rule, say the two passwords must match, use setCustomValidity on the field. An empty string clears it again.
Finally, send it with fetch, show a loading state on the button, and put the result on the page. That's the whole pattern, and it's the last piece your three apps need.