Contact Form examples
네이티브 유효성 검사, 인라인 에러 메시지, 접근성 있는 제출 상태를 갖춘 레이블이 지정된 문의 폼입니다.
표시되는 레이블, 인라인 유효성 검사 메시지, 접근성 있는 제출 상태를 갖춘 문의 폼입니다. 모든 필드는 해당 레이블과 올바르게 연결되어 있으며, 에러는 단순 시각적 표시를 넘어 aria-describedby를 통해 안내되도록 설정되어 있습니다.
첫 번째 variant는 제출 시 유효성을 검사하고 필드별 에러를 렌더링합니다. 나머지는 네이티브 브라우저 유효성 검사에 의존하는 정적 마크업입니다.
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?
문의 폼은 방문자가 사이트 소유자에게 연락하는 가장 일반적인 방법이자, 작은 구현 실수 하나가 곧바로 메시지 손실로 이어지는 몇 안 되는 장소 중 하나입니다. 추가되는 필수 필드, 불명확한 에러, 자동완성으로 인식할 수 없는 모든 입력은 누군가 연락을 결심한 바로 그 순간에 마찰을 발생시킵니다.
기본적인 요소들은 화려하지 않아서 자주 간과됩니다. 모든 입력에는 플레이스홀더가 아니라 id로 연결된 실제 label 엘리먼트가 필요합니다. 플레이스홀더는 타이핑이 시작되면 사라지므로 입력 위치를 잃어버린 사람이 필드의 의미를 다시 파악할 방법이 없어지고, 스크린 리더에서도 안정적으로 읽히지 않습니다. autocomplete 속성도 이와 같은 실용적인 이유로 중요합니다. 이를 사용하면 브라우저가 한 번의 탭으로 이름과 이메일을 채워주지만, 없으면 사용자가 휴대폰 키보드로 둘 다 직접 입력해야 합니다.
유효성 검사는 대부분의 폼에서 답답함을 느끼는 부분입니다. 키를 누를 때마다 유효성을 검사하는 것은 사용자가 아직 세 번째 글자를 입력하는 중에 이메일이 유효하지 않다고 알려주는 셈입니다. 제출할 때만 검사하고 설명 없이 필드를 빨간색으로만 강조하면 사용자는 원인을 추측해야 합니다. 효과적인 절충안은 필드별 구체적인 메시지와 함께 제출 시점에 유효성을 검사하고, 수정됨에 따라 해당 필드를 재검사하여 올바르게 수정되면 에러가 사라지도록 하는 것입니다.
제출 상태는 겉보기보다 훨씬 중요합니다. 피드백을 주지 않는 버튼은 두 번째 클릭을 유도하며, 보호되지 않은 폼에서의 두 번째 클릭은 중복 메시지를 전송하게 됩니다. 제출 중 버튼을 비활성화하고 레이블을 변경하는 것으로 이를 처리할 수 있으며, polite live region은 메시지가 나타나는 것을 볼 수 없는 사용자에게 최종 확인을 전달합니다.
Anatomy
- Field group
- 필드 간의 간격이 일정하게 유지되도록 레이블, 컨트롤, 힌트 또는 에러 메시지를 하나로 묶은 그룹입니다.
- Label
- 입력 요소의 id와 일치하는 for 속성을 가진 실제 label 엘리먼트입니다. 레이블을 클릭할 수 있게 만들고 입력에 접근성 이름을 부여하는 역할을 합니다.
- Control
- 폼 데이터를 위한 name, 올바른 모바일 키보드를 위한 type, 브라우저 채우기를 위한 autocomplete 토큰을 포함하는 input 또는 textarea입니다.
- Hint
- 그렇지 않으면 플레이스홀더에 들어갈 내용을 위해 aria-describedby로 연결된 선택적 지원 텍스트입니다.
- Error message
- 필드 검사에 실패했을 때 힌트를 대체합니다. 역시 aria-describedby로 연결되며 컨트롤의 aria-invalid와 쌍을 이룹니다.
- Submit button
- Enter 키로 폼이 제출되도록 하는 실제 제출 버튼입니다. 전송 중에는 비활성화되며 현재 상태를 반영하는 레이블을 표시합니다.
- Status region
- 성공 메시지를 전달하는 polite live region으로, 단순히 화면에 나타나는 것뿐만 아니라 음성으로도 안내되도록 합니다.
How to Use
- 1
Copy the form
네이티브 브라우저 유효성 검사를 사용하려면 HTML 버전을 선택하고, 커스텀 메시지와 제어되는 제출 상태를 사용하려면 React 버전을 선택하세요.
- 2
Connect your endpoint
주석 처리된 fetch 호출을 API 라우트, 폼 서비스 또는 서버 액션으로 교체하세요. 폼 데이터는 이미 FormData 객체로 수집되어 있습니다.
- 3
Adjust the fields
필요에 따라 필드 그룹을 추가하거나 제거하세요. 각 그룹에는 일치하는 label의 for와 input의 id 쌍이 필요합니다. 이 연결이 필드를 사용 가능하게 만듭니다.
- 4
Set autocomplete tokens
표 standard 값을 사용하세요: name, email, tel, organization. 브라우저가 모바일에서 탭 한 번으로 폼을 채울 수 있도록 해줍니다.
- 5
응답 처리
성공 시 상태를 sent로 설정하고 실패 시 구체적인 메시지를 띄우세요. 성공한 것처럼 보이는 실패는 오류보다 더 나쁩니다.
Features
모든 필드에 실제 label 제공
각 label은 id로 연결되어 클릭이 가능하며, placeholder가 제대로 하지 못하는 역할을 대신하여 입력에 접근 가능한 이름을 부여합니다.
필드와 연결된 에러
메시지는 aria-describedby로 연결되고 컨트롤에는 aria-invalid가 적용되어, 에러가 단순히 눈에 보이는 것뿐만 아니라 필드에 포커스가 갔을 때 음성으로 안내됩니다.
자동 완성(Autocomplete) 지원
모든 필드의 표준 토큰을 통해 브라우저와 비밀번호 관리자가 한 번의 동작으로 폼을 채울 수 있습니다. 이는 탭 한 번과 엄지손가락으로 문장을 타이핑하는 것의 차이입니다.
중복 제출 방지
전송 중에는 버튼이 비활성화되고 라벨이 변경되어 중복 메시지를 보내는 더블 클릭을 방지합니다.
안내되는 확인 메시지
성공 메시지는 polite live region에 위치하여, 조용히 나타나는 대신 스크린 리더 사용자에게 전달됩니다.
올바른 모바일 키보드
필드별로 input type이 설정되어 있으므로, 이메일 필드는 골뱅이(@) 기호를 찾을 필요 없이 바로 입력할 수 있는 키보드를 띄웁니다.
Common Uses
사이트 문의 페이지
일반적인 문의를 위한 표준 name, email, 메시지 폼으로, 유용한 답변을 받을 수 있는 최소한의 필드만 유지하는 것이 목표입니다.
영업 및 데모 요청
회사 필드와 주제 선택을 추가하여, 방문자가 어떤 받은편지함으로 보내야 할지 고민하지 않고도 문의를 라우팅할 수 있습니다.
지원 요청
카테고리 선택 및 선택적 주문 또는 계정 참조를 결합하여, 첫 답변이 단순히 추가 정보를 요구하는 대신 유용할 수 있도록 합니다.
피드백 및 버그 리포트
선택적 이메일이 포함된 메시지 필드로, 이메일을 선택 사항으로 만들면 접수되는 리포트 수가 의미 있게 증가합니다.
Accessibility
- 모든 컨트롤에는 for와 id로 연결된 label 요소가 있어 접근 가능한 이름을 제공하고, 라벨 텍스트를 인풋의 클릭 타겟으로 만들어 줍니다.
- Placeholder는 절대 라벨로 사용하지 마세요. 인풋에 입력하는 순간 사라지고 안정적으로 음성 안내가 되지 않으므로, 중요한 내용은 라벨이나 힌트에 들어가야 합니다.
- 에러 메시지는 aria-describedby로 연결되고 컨트롤은 aria-invalid를 가지므로, 필드가 포커스를 받을 때 에러가 안내됩니다.
- 힌트와 에러는 필드당 하나의 슬롯을 공유하므로, 하나의 필드가 동시에 상반된 두 가지 메시지로 설명되지 않습니다.
- 제출 컨트롤은 type이 submit인 실제 버튼이므로, 어떤 필드에서든 Enter 키를 누르면 예상대로 폼이 제출됩니다.
- 성공 메시지는 aria-live가 polite로 설정된 영역에 위치하여, 읽고 있는 내용을 방해하지 않고 결과를 안내합니다.
- 포커스 스타일은 버튼에 focus-visible을, 필드에 링을 사용하므로 폼 전체에서 키보드 위치가 명확하게 유지됩니다.
Customization
- React 버전처럼 필드 클래스를 공유 상수로 추출하여, 폼이 커져도 모든 인풋이 시각적으로 일관성을 유지하도록 하세요.
- 포커스 링과 테두리 클래스를 함께 수정하여 포커스 처리를 변경하세요. 하나만 변경하면 필드가 절반만 포커스된 것처럼 보입니다.
- grid를 사용하여 sm 이상에서는 연관된 필드를 두 개의 열로 짝지어 배치하되, 연관 없는 필드는 단일 열로 유지하세요. 무작위로 흩어진 2열 폼은 작성 완료하는 데 더 오래 걸립니다.
- 플로팅 라벨 스타일의 경우, 실제 label 요소를 placeholder로 대체하는 대신 그대로 유지하고 위치를 애니메이션 처리하세요.
- 대부분의 필드가 필수인 경우 필수 필드 대신 선택 필드에 표시를 하세요. 표시가 적을수록 중요한 필드의 시각적 노이즈가 줄어듭니다.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
| onSubmit | (data: FormData) => Promise<void> | - | 유효성 검사가 통과되면 폼 데이터와 함께 호출됩니다. 동일한 폼을 서로 다른 엔드포인트로 보낼 수 있도록 네트워크 호출은 컴포넌트 외부에서 유지하세요. |
| successMessage | string | "Thanks - we will reply shortly." | 성공적으로 제출된 후 polite live region을 통해 안내되므로, 화면을 볼 수 있는 사용자뿐만 아니라 스크린 리더 사용자도 확인 메시지를 전달받을 수 있습니다. |
Why Use These Contact Forms?
눈에 띄지 않는 기본적인 부분들을 제대로 구현합니다. id로 연결된 라벨, 자동 완성 토큰, 에러의 aria-describedby, 그리고 중복 제출 방지는 모두를 위한 폼과 개발자만을 위한 폼의 차이를 만듭니다.
유효성 검사는 타이핑하는 동안 이메일이 유효하지 않다고 표시하는 방식 대신, 제출 시에 실행되고 필드별로 지워집니다. 후자의 방식은 많은 폼을 거부감 들게 만드는 요인입니다.
폼 라이브러리가 없습니다. 세 개의 필드만 있는 경우 스키마 밸리데이터와 폼 상태 패키지는 폼 자체보다 설정이 더 복잡하며, 접근성 연결 작업은 여전히 개발자의 몫으로 남겨둡니다.
Tips
- 실제로 처리가 가능한 최소한의 필드만 요청하세요. 선택적 필드를 추가할 때마다 완료된 제출 건수가 줄어듭니다.
- 플레이스홀더를 라벨로 절대 사용하지 마세요. 첫 글자를 입력하는 순간 사라지므로, 잠시 시선을 놓친 사용자는 해당 필드가 무엇을 위한 것이었는지 알 방법이 없습니다.
- 모든 필드에 autocomplete 토큰을 설정하세요. 스마트폰에서는 탭 한 번으로 끝내느냐, 엄지손가락으로 이메일 주소를 직접 타이핑하느냐의 차이를 만듭니다.
- '올바른 이메일 주소를 입력하세요'처럼 오류를 지침 형태로 작성하세요. 무엇을 해야 할지 알려주는 반면, '잘못된 입력입니다'는 무언가 잘못되었다는 사실만 알려줄 뿐입니다.
- UI뿐만 아니라 서버에서도 중복 제출을 방지하세요. 비활성화된 버튼은 도움이 되지만 보장이 되지는 않습니다.
- 화면에서 숨겨진 허니팟 필드를 추가하고 여기에 값이 채워진 제출 건은 무시하세요. 실제 방문자에게는 아무런 영향 없이 대다수의 자동화된 스팸을 제거해 줍니다.
- textarea의 크기 조절이 가능하도록 유지하세요. 크기 조절을 없애는 것은 흔한 스타일링 결정이지만, 아무런 이점 없이 긴 메시지를 작성하는 과정을 불편하게 만듭니다.