Contact Form examples
Native validation, inline error messages, aur ek accessible submit state ke sath ek labelled contact form.
Visible labels, inline validation messages, aur ek accessible submit state wala contact form. Har field apne label ke sath theek se associated hoti hai, aur errors aria-describedby ke zariye wired hote hain taake sirf dikhne ke bajaye announce kiye jayein.
Pehli variant submit par validate karti hai aur per-field errors render karti hai. Baaki static markup hain jo native browser validation par depend karte hain.
Contact form with inline validation
Name, email, and message with labels connected by id, per-field error messages wired through aria-describedby, and a submit button that guards against double sends.
"use client";
import { useState } from "react";
type Errors = Partial<Record<"name" | "email" | "message", string>>;
export default function ContactForm() {
const [errors, setErrors] = useState<Errors>({});
const [status, setStatus] = useState<"idle" | "sending" | "sent">("idle");
async function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
event.preventDefault();
const data = new FormData(event.currentTarget);
const next: Errors = {};
if (!String(data.get("name") ?? "").trim()) {
next.name = "Enter your name.";
}
if (!String(data.get("email") ?? "").includes("@")) {
next.email = "Enter a valid email address.";
}
if (!String(data.get("message") ?? "").trim()) {
next.message = "Enter a message.";
}
setErrors(next);
if (Object.keys(next).length > 0) return;
setStatus("sending");
// await fetch("/api/contact", { method: "POST", body: data });
setStatus("sent");
}
const field =
"mt-1.5 block w-full rounded-md border px-3 py-2 text-sm text-gray-900 focus:outline-none focus:ring-1";
const ok = "border-gray-300 focus:border-gray-900 focus:ring-gray-900";
const bad = "border-red-500 focus:border-red-500 focus:ring-red-500";
return (
<form onSubmit={handleSubmit} className="mx-auto max-w-lg space-y-5" noValidate>
<div>
<label htmlFor="name" className="block text-sm font-medium text-gray-900">
Name
</label>
<input
id="name"
name="name"
type="text"
autoComplete="name"
aria-invalid={Boolean(errors.name)}
aria-describedby={errors.name ? "name-error" : undefined}
className={field + " " + (errors.name ? bad : ok)}
/>
{errors.name && (
<p id="name-error" className="mt-1.5 text-xs text-red-600">
{errors.name}
</p>
)}
</div>
<div>
<label htmlFor="email" className="block text-sm font-medium text-gray-900">
Email
</label>
<input
id="email"
name="email"
type="email"
autoComplete="email"
aria-invalid={Boolean(errors.email)}
aria-describedby={errors.email ? "email-error" : "email-hint"}
className={field + " " + (errors.email ? bad : ok)}
/>
{errors.email ? (
<p id="email-error" className="mt-1.5 text-xs text-red-600">
{errors.email}
</p>
) : (
<p id="email-hint" className="mt-1.5 text-xs text-gray-500">
We will only use this to reply.
</p>
)}
</div>
<div>
<label htmlFor="message" className="block text-sm font-medium text-gray-900">
Message
</label>
<textarea
id="message"
name="message"
rows={5}
aria-invalid={Boolean(errors.message)}
aria-describedby={errors.message ? "message-error" : undefined}
className={field + " " + (errors.message ? bad : ok)}
/>
{errors.message && (
<p id="message-error" className="mt-1.5 text-xs text-red-600">
{errors.message}
</p>
)}
</div>
<button
type="submit"
disabled={status === "sending"}
className="w-full rounded-md bg-gray-900 px-4 py-2.5 text-sm font-medium text-white hover:bg-gray-700 disabled:opacity-60 focus:outline-none focus-visible:ring-2 focus-visible:ring-gray-900 focus-visible:ring-offset-2"
>
{status === "sending" ? "Sending..." : "Send message"}
</button>
<p aria-live="polite" className="text-sm text-gray-600">
{status === "sent" ? "Thanks - we will reply shortly." : ""}
</p>
</form>
);
}Contact form with two-column fields
Name and email side by side from the sm breakpoint, stacked below it. Only pair fields that are genuinely related.
export default function TwoColumnContactForm() {
return (
<form className="mx-auto max-w-lg space-y-5" noValidate>
<div className="grid gap-5 sm:grid-cols-2">
<div>
<label htmlFor="name" className="block text-sm font-medium text-gray-900">Name</label>
<input id="name" name="name" type="text" required autoComplete="name" className="mt-1.5 block w-full rounded-md border border-gray-300 px-3 py-2 text-sm text-gray-900 placeholder:text-gray-400 focus:border-gray-900 focus:outline-none focus:ring-1 focus:ring-gray-900" />
</div>
<div>
<label htmlFor="email" className="block text-sm font-medium text-gray-900">Email</label>
<input id="email" name="email" type="email" required autoComplete="email" className="mt-1.5 block w-full rounded-md border border-gray-300 px-3 py-2 text-sm text-gray-900 placeholder:text-gray-400 focus:border-gray-900 focus:outline-none focus:ring-1 focus:ring-gray-900" />
</div>
</div>
<div>
<label htmlFor="message" className="block text-sm font-medium text-gray-900">Message</label>
<textarea id="message" name="message" rows="5" required className="mt-1.5 block w-full rounded-md border border-gray-300 px-3 py-2 text-sm text-gray-900 placeholder:text-gray-400 focus:border-gray-900 focus:outline-none focus:ring-1 focus:ring-gray-900"></textarea>
</div>
<button type="submit" className="w-full rounded-md bg-gray-900 px-4 py-2.5 text-sm font-medium text-white hover:bg-gray-700 focus:outline-none focus-visible:ring-2 focus-visible:ring-gray-900 focus-visible:ring-offset-2">Send message</button>
</form>
);
}Contact form with a subject select
A subject dropdown for routing enquiries to the right inbox. Keep the options short and concrete rather than naming internal teams.
export default function ContactFormWithSubject() {
return (
<form className="mx-auto max-w-lg space-y-5" noValidate>
<div>
<label htmlFor="name" className="block text-sm font-medium text-gray-900">Name</label>
<input id="name" name="name" type="text" required autoComplete="name" className="mt-1.5 block w-full rounded-md border border-gray-300 px-3 py-2 text-sm text-gray-900 placeholder:text-gray-400 focus:border-gray-900 focus:outline-none focus:ring-1 focus:ring-gray-900" />
</div>
<div>
<label htmlFor="email" className="block text-sm font-medium text-gray-900">Email</label>
<input id="email" name="email" type="email" required autoComplete="email" className="mt-1.5 block w-full rounded-md border border-gray-300 px-3 py-2 text-sm text-gray-900 placeholder:text-gray-400 focus:border-gray-900 focus:outline-none focus:ring-1 focus:ring-gray-900" />
</div>
<div>
<label htmlFor="subject" className="block text-sm font-medium text-gray-900">Subject</label>
<select id="subject" name="subject" className="mt-1.5 block w-full rounded-md border border-gray-300 px-3 py-2 text-sm text-gray-900 placeholder:text-gray-400 focus:border-gray-900 focus:outline-none focus:ring-1 focus:ring-gray-900 bg-white">
<option>General question</option>
<option>Sales and pricing</option>
<option>Technical support</option>
<option>Press</option>
</select>
</div>
<div>
<label htmlFor="message" className="block text-sm font-medium text-gray-900">Message</label>
<textarea id="message" name="message" rows="5" required className="mt-1.5 block w-full rounded-md border border-gray-300 px-3 py-2 text-sm text-gray-900 placeholder:text-gray-400 focus:border-gray-900 focus:outline-none focus:ring-1 focus:ring-gray-900"></textarea>
</div>
<button type="submit" className="w-full rounded-md bg-gray-900 px-4 py-2.5 text-sm font-medium text-white hover:bg-gray-700 focus:outline-none focus-visible:ring-2 focus-visible:ring-gray-900 focus-visible:ring-offset-2">Send message</button>
</form>
);
}Contact section with details beside the form
Contact details on the left and the form on the right at md, stacked on mobile. A complete contact-page section.
export default function ContactSection() {
return (
<section className="mx-auto grid max-w-5xl gap-10 px-4 py-12 md:grid-cols-2">
<div className="bg-gray-900 p-4 rounded-lg">
<h2 className="text-2xl font-bold text-gray-100">Get in touch</h2>
<p className="mt-3 text-sm text-white">Tell us what you are working on and we will reply within one business day.</p>
<dl className="mt-8 space-y-4 text-sm">
<div>
<dt className="font-medium text-gray-100">Email</dt>
<dd className="text-white">hello@example.com</dd>
</div>
<div>
<dt className="font-medium text-gray-100">Office hours</dt>
<dd className="text-white">Monday to Friday, 9am to 5pm</dd>
</div>
</dl>
</div>
<form className="space-y-5" noValidate>
<div>
<label htmlFor="name" className="block text-sm font-medium text-gray-900">Name</label>
<input id="name" name="name" type="text" required autoComplete="name" className="mt-1.5 block w-full rounded-md border border-gray-300 px-3 py-2 text-sm text-gray-900 placeholder:text-gray-400 focus:border-gray-900 focus:outline-none focus:ring-1 focus:ring-gray-900" />
</div>
<div>
<label htmlFor="email" className="block text-sm font-medium text-gray-900">Email</label>
<input id="email" name="email" type="email" required autoComplete="email" className="mt-1.5 block w-full rounded-md border border-gray-300 px-3 py-2 text-sm text-gray-900 placeholder:text-gray-400 focus:border-gray-900 focus:outline-none focus:ring-1 focus:ring-gray-900" />
</div>
<div>
<label htmlFor="message" className="block text-sm font-medium text-gray-900">Message</label>
<textarea id="message" name="message" rows="5" required className="mt-1.5 block w-full rounded-md border border-gray-300 px-3 py-2 text-sm text-gray-900 placeholder:text-gray-400 focus:border-gray-900 focus:outline-none focus:ring-1 focus:ring-gray-900"></textarea>
</div>
<button type="submit" className="w-full rounded-md bg-gray-900 px-4 py-2.5 text-sm font-medium text-white hover:bg-gray-700 focus:outline-none focus-visible:ring-2 focus-visible:ring-gray-900 focus-visible:ring-offset-2">Send message</button>
</form>
</section>
);
}What is a Contact Form?
Contact form sab se common tareeqa hai jisse koi visitor site ke owner tak pohchta hai, aur yeh un chand jagahon mein se hai jahan choti si implementation mistake ki wajah se seedha ek message miss ho jata hai. Har additional required field, har unclear error, aur har woh input jise autofill recognize na kar sake, uss waqt friction paida karta hai jab kisi ne rabta karne ka faisla kiya ho.
Fundamentals simple hain lekin aksar skip kar diye jate hain. Har input ko id se connect hua aik real label element chahiye, na ke placeholder jo label ki jagah le le - placeholder type karna shuru karte hi gayab ho jata hai, jis se jin logon ka focus hate unhe field ka meaning wapas samajhne ka koi rasta nahi milta, aur screen readers bhi inhein reliably announce nahi karte. Autocomplete attributes bhi same practical reason ki wajah se zaroori hain: inke sath browser ek tap mein name aur email fill kar deta hai, aur inke baghair person phone keyboard par dono manually type karta hai.
Validation woh jagah hai jahan zyadatar forms frustrating ho jate hain. Har keystroke par validate karne ka matlab hai kisi ko yeh batana ke unka email invalid hai jabke woh abhi teesre character par hain. Sirf submit par validate karna, aur phir bina kisi explanation ke fields ko sirf red highlight karna, unhein andhaze mein chhor deta hai. Behtareen rasta yeh hai ke submit par har field ke specific message ke sath validate kiya jaye, aur phir jab field theek ho to use revalidate kiya jaye taake error khatam ho jaye.
Submit state jitni dikhti hai us se zyada zaroori hai. Ek button jo koi feedback na de woh dusre click ki dawat deta hai, aur unguarded form par dusra click duplicate message bhej deta hai. Submission ke doran button ko disable karna aur uska label change karna isay handle karta hai, aur ek polite live region final confirmation un logon tak pohchati hai jo message ko screen par aate hue nahi dekh sakte.
Anatomy
- Field group
- Ek label, uska control, aur uska hint ya error message, aik sath wrapped taake teeno ke darmiyan spacing har field mein consistent rahe.
- Label
- Ek real label element jisme input ke id se match karta hua for attribute ho. Isi se label clickable banta hai aur input ko ek accessible name milta hai.
- Control
- Input ya textarea, jo form data ke liye name, sahi mobile keyboard ke liye type, aur browser fill ke liye autocomplete token rakhta hai.
- Hint
- Optional supporting text jo aria-describedby se connected ho, kisi bhi aisi cheez ke liye use hota hai jo aam tor par placeholder mein jati.
- Error message
- Jab koi field fail ho jaye to hint ki jagah le leta hai. Yeh bhi aria-describedby se connected hota hai, aur control par aria-invalid ke sath paired hota hai.
- Submit button
- Ek real submit button taake Enter dabane se form submit ho jaye. Bhejne ke doran disabled rehta hai, aur ek aise label ke sath jo current state ko reflect kare.
- Status region
- Success message ko carry karne wala ek polite live region, taake confirmation sirf screen par aane ke bajaye announce ki jaye.
How to Use
- 1
Form copy karein
Native browser validation ke liye HTML version lein, ya custom messages aur controlled submit state ke liye React version lein.
- 2
Apna endpoint connect karein
Commented fetch call ko apne API route, form service, ya server action se replace karein. Form data pehle hi ek FormData object ke tor par collect ho chuka hai.
- 3
Fields adjust karein
Zaroorat ke mutabiq field groups add ya remove karein. Har ek ko ek matching label for aur input id pair chahiye - yeh connection hi field ko usable banata hai.
- 4
Autocomplete tokens set karein
Standard values use karein: name, email, tel, organization. Yehi wo cheezein hain jo browser ko phone par aik hi tap mein form fill karne deti hain.
- 5
Response ko handle karein
Success hone par status ko sent par set karein aur fail hone par aik specific message show karein. Aik failed send jo successful jaisa lagta hai, error se bhi zyada bura hota hai.
Features
Har field par real labels
Har label id ke zariye connected hota hai, jisse wo clickable ban jata hai aur input ko aik accessible name milta hai - na ke placeholder jo ye kaam buri tarah karta hai.
Errors unke fields ke sath wired hote hain
Messages aria-describedby aur control par aria-invalid ke zariye connected hote hain, taake jab field par focus ho to error sirf nazar hi na aaye balkay announce bhi ho.
Autocomplete support
Har field par standard tokens browsers aur password managers ko aik hi action mein form fill karne ki ijazat dete hain, jo aik tap aur anguthe se lambi typing karne ke darmiyan ka farq hai.
Guarded submit
Button sending ke doran disable ho jata hai aur iska label change ho jata hai, jo double-click ko roakta hai jis se duplicate messages chale jate hain.
Announced confirmation
Success message aik polite live region mein hota hai, taake wo chup chaap nazar aane ke bajaye screen reader use karne walon tak pohnch jaye.
Sahi mobile keyboards
Input types har field ke hisab se set hote hain, is liye email field aik aisa keyboard lata hai jis par @ ka sign hota hai, bajaye iske ke log isay dhoondte phiren.
Common Uses
Site contact pages
General enquiries ke liye standard name, email, aur message form, jahan maqsad kam se kam fields rakhna hai jo phir bhi aapko useful reply dene ke kabil banayein.
Sales aur demo requests
Company field aur subject select ke sath extended, jo visitor ko ye guess karwaye baghair enquiries ko route karta hai ke kis inbox mein likhna hai.
Support requests
Category select aur optional order ya account reference ke sath paired, taake pehla reply details ki request karne ke bajaye useful ho sake.
Feedback aur bug reports
Aik message field jiske sath optional email ho, jahan email ko optional banana milne wali reports ki tadaad mein waqai izafa karta hai.
Accessibility
- Har control mein aik label element hota hai jo for aur id se connected hota hai, jo isay aik accessible name deta hai aur label text ko input ke liye click target banata hai.
- Placeholders ko kabhi bhi labels ke tor par use nahi kiya jata. Ye input karte hi gayab ho jate hain aur inhein reliable tarike se announce nahi kiya jata, is liye koi bhi zaroori cheez label ya hint mein honi chahiye.
- Error messages aria-describedby se connected hote hain aur control par aria-invalid hota hai, is liye jab field par focus milta hai to error announce ho jata hai.
- Hint aur error har field ke liye aik slot share karte hain, is liye koi bhi field aik waqt mein do mukhalif messages se describe nahi hoti.
- Submit control type submit ke sath aik real button hota hai, is liye kisi bhi field mein Enter dabane se form expected tareeqay se submit ho jata hai.
- Success message aik aisi region mein hota hai jahan aria-live polite par set hota hai, jo jo kuch bhi parha ja raha hai usay interrupt kiye baghair result announce karta hai.
- Focus styles button par focus-visible aur fields par ring use karte hain, taake pure form mein keyboard ki position clear rahe.
Customization
- Field classes ko aik shared constant mein extract karein, jaisa ke React version karta hai, taake jaise jaise form barhe har input visually consistent rahe.
- Focus ring aur border classes ko ikathay edit karke focus treatment change karein. Sirf aik ko change karne se aisi field banti hai jo adhi-focused lagti hai.
- Grid ke sath sm se upar related fields ko do columns mein pair karein, lekin unrelated fields ko aik hi column mein rakhein - bikhre hue do-column forms ko complete karna mushkil hota hai.
- Floating-label style ke liye, real label element ko rakhein aur placeholder se replace karne ke bajaye iski position ko animate karein.
- Jab zyada tar fields required hon to required ke bajaye optional fields ko mark karein. Kam markers ka matlab hai zaroori fields par kam visual noise.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
| onSubmit | (data: FormData) => Promise<void> | - | Validation pass hone ke baad form data ke sath call hota hai. Network call ko component se bahar rakhein taake same form alag alag endpoints par post ho sake. |
| successMessage | string | "Thanks - we will reply shortly." | Successful submit ke baad ek polite live region ke zariye announce kiya jata hai, taake confirmation screen reader users aur dekhte hue users dono tak pohch jaye. |
Why Use These Contact Forms?
Ye unglamorous parts ko theek karta hai. Id se connected labels, autocomplete tokens, errors par aria-describedby, aur guarded submit aik aise form mein farq paida karte hain jo sab ke liye kaam kare aur jo sirf banane wale ke liye kaam kare.
Validation submit par run hoti hai aur per field clear hoti hai, bajaye iske ke email ke type hote waqt hi usay invalid mark kar diya jaye - wo behavior jo bohat sare forms ko hostile mehsoos karwata hai.
Koi form library nahi. Sirf teen fields ke liye, ek schema validator aur form state package form khud se zyada configuration maangte hain, aur accessibility ki wiring phir bhi aapko hi karni padti hai.
Tips
- Sirf wohi fields maangein jin par aap actually action le sakein. Aap jo bhi optional field add karte hain, woh completed submissions ki tadad ko kam kar deta hai.
- Kabhi bhi placeholder ko label ke taur par use na karein. Pehli keystroke par woh gayab ho jata hai, aur jis ka bhi dhyan bhatak jaye, uske paas yeh jaanne ka koi tareeqa nahi hota ke field kis cheez ke liye thi.
- Har field par autocomplete tokens set karein. Phone par yeh ek tap aur anguthe se email address type karne ke beech ka farq hota hai.
- Errors ko instructions ki tarah likhein. 'Enter a valid email address' kisi ko batata hai ke kya karna hai; 'Invalid input' sirf yeh batata hai ke kuch galat hai.
- UI ke sath sath server par bhi double submission se bachein. Ek disabled button madad karta hai, lekin yeh koi guarantee nahi hai.
- Ek honeypot field add karein jo nazar se chupa ho aur usme aane wali submissions ko ignore kar dein. Yeh asli visitors par asar dale bina automated spam ka aik bara hissa khatam kar deta hai.
- Textarea ko resizable rakhein. Resize khatam karna ek aam styling decision hai jo bina kisi faide ke lamba message likhna mushkil bana deta hai.