Build HTML Forms in Astro Pages
Dieser Inhalt ist noch nicht in deiner Sprache verfügbar.
PrerequisitesSection titled Prerequisites
- A project with SSR (
output: 'server') enabled
RecipeSection titled Recipe
Create or identify a
.astropage which will contain your form and your handling code. For example, you could add a registration page:
<form>tag with some inputs to the page. Each input should have a
nameattribute that describes the value of that input.
Be sure to include a
<input type="submit">element to submit the form.
In this example,
requiredprevents form submission until the field is filled.
minlengthsets a minimum required length for the input text.
type="email"also introduces validation that will only accept a valid email format.
The form submission will cause the browser to request the page again. Change the form’s data transfer
POSTto send the form data as part of the
Requestbody, rather than as URL parameters.
Check for the
POSTmethod in the frontmatter and access the form data using
Astro.request.formData(). Wrap this in a
try ... catchblock to handle cases when the
POSTrequest wasn’t sent by a form and the
Validate the form data on the server. This should include the same validation done on the client to prevent malicious submissions to your endpoint and to support the rare legacy browser that doesn’t have form validation.
It can also include validation that can’t be done on the client. For example, this example checks if the email is already in the database.
Error messages can be sent back to the client by storing them in an
errorsobject and accessing it in the template.