fix(forms): repair public form validation and reset
This commit is contained in:
parent
3456b04ed4
commit
7d5689cfa4
4 changed files with 24 additions and 17 deletions
|
|
@ -1,8 +1,9 @@
|
|||
"use client";
|
||||
|
||||
import { useState, type FormEvent } from "react";
|
||||
import { useRef, useState, type FormEvent } from "react";
|
||||
|
||||
export default function ContactForm() {
|
||||
const formRef = useRef<HTMLFormElement>(null);
|
||||
const [message, setMessage] = useState("");
|
||||
const [error, setError] = useState("");
|
||||
const [pending, setPending] = useState(false);
|
||||
|
|
@ -16,8 +17,9 @@ export default function ContactForm() {
|
|||
const email = String(form.get("email") ?? "").trim();
|
||||
const subject = String(form.get("subject") ?? "").trim();
|
||||
const text = String(form.get("message") ?? "").trim();
|
||||
const privacyAccepted = form.get("privacyAccepted") === "on";
|
||||
|
||||
if (!name || !email.includes("@") || !subject || text.length < 10 || form.get("privacy") !== "on") {
|
||||
if (!name || !email.includes("@") || !subject || text.length < 10 || !privacyAccepted) {
|
||||
setError("Bitte füllen Sie alle Pflichtfelder aus und bestätigen Sie die Datenschutz-Hinweise.");
|
||||
return;
|
||||
}
|
||||
|
|
@ -27,17 +29,17 @@ export default function ContactForm() {
|
|||
const response = await fetch("/api/contact", { method: "POST", body: form });
|
||||
const result = await response.json() as { message?: string };
|
||||
if (!response.ok) throw new Error(result.message ?? "Nachricht konnte nicht gesendet werden.");
|
||||
event.currentTarget.reset();
|
||||
formRef.current?.reset();
|
||||
setMessage(result.message ?? "Ihre Nachricht wurde vorbereitet.");
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Nachricht konnte nicht gesendet werden.");
|
||||
setError(err instanceof Error ? err.message : "Nachricht konnte nicht gesendet werden. Bitte versuchen Sie es später erneut.");
|
||||
} finally {
|
||||
setPending(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form className="form" onSubmit={submit} noValidate>
|
||||
<form ref={formRef} className="form" onSubmit={submit} noValidate>
|
||||
<div className="field">
|
||||
<label htmlFor="name">Name</label>
|
||||
<input id="name" name="name" />
|
||||
|
|
@ -59,7 +61,7 @@ export default function ContactForm() {
|
|||
<textarea id="message" name="message" />
|
||||
</div>
|
||||
<label className="checkbox">
|
||||
<input type="checkbox" name="privacy" />
|
||||
<input type="checkbox" name="privacyAccepted" />
|
||||
<span>Ich stimme zu, dass meine Angaben zur Bearbeitung der Kontaktanfrage verarbeitet werden.</span>
|
||||
</label>
|
||||
{error && <p className="error">{error}</p>}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue