¡Nuevas herramientas añadidas! Descubre las novedades

Inicio/Componentes/Formulario de contacto

Formulario de contacto examples

Un formulario de contacto etiquetado con validación nativa, mensajes de error en línea y un estado de envío accesible.

Un formulario de contacto con etiquetas visibles, mensajes de validación en línea y un estado de envío accesible. Cada campo está correctamente asociado con su etiqueta, y los errores se conectan mediante aria-describedby para que se anuncien en lugar de solo mostrarse.

La primera variante valida al enviar y muestra errores por campo. Las otras son marcado estático que confía en la validación nativa del navegador.

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.

Preview
"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.

Preview
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.

Preview
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>
  );
}

Inline newsletter signup form

A single email field with the button on the same row, for footers and banners where a full form is too heavy.

Preview
export default function NewsletterForm() {
  return (
    <form className="mx-auto max-w-md" noValidate>
      <label htmlFor="newsletter-email" className="block text-sm font-medium text-gray-900">Get product updates</label>
      <div className="mt-1.5 flex gap-2">
        <input
          id="newsletter-email"
          name="email"
          type="email"
          required
          autoComplete="email"
          placeholder="you@example.com"
          className="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"
        />
        <button type="submit" className="shrink-0 rounded-md bg-gray-900 px-4 py-2 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">Subscribe</button>
      </div>
      <p className="mt-2 text-xs text-gray-500">One email a month. Unsubscribe any time.</p>
    </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.

Preview
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 Formulario de contacto?

Un formulario de contacto es la forma más común en que un visitante se comunica con el propietario de un sitio, y uno de los pocos lugares donde un pequeño error de implementación cuesta directamente un mensaje. Cada campo obligatorio adicional, cada error poco claro y cada input que el autocomllenado no puede reconocer añade fricción justo en el momento en que alguien decidió ponerse en contacto.

Los fundamentos no son glamurosos y se omiten con frecuencia. Cada input necesita un elemento label real conectado por id, no un marcador de posición (placeholder) que haga sus veces - los marcadores de posición desaparecen al empezar a escribir, dejando a quienes pierden el hilo sin forma de recuperar el significado del campo, y los lectores de pantalla no los anuncian de manera fiable. Los atributos autocomplete importan por la misma razón práctica: con ellos, un navegador rellena un nombre y un correo electrónico con un toque, y sin ellos la persona los escribe a mano en el teclado de un teléfono.

La validación es donde la mayoría de los formularios resultan frustrantes. Validar en cada pulsación de tecla significa decirle a alguien que su correo no es válido mientras aún está en el tercer carácter. Validar solo al enviar, y luego solo resaltar los campos en rojo sin explicación, les deja adivinando. El punto medio que funciona es validar al enviar con un mensaje específico por campo, y luego volver a validar ese campo a medida que se corrige para que el error desaparezca cuando se arregle.

El estado de envío importa más de lo que parece. Un botón que no da retroalimentación invita a un segundo clic, y un segundo clic en un formulario no protegido envía un mensaje duplicado. Deshabilitar el botón durante el envío y cambiar su etiqueta maneja eso, y una live region educada transmite la confirmación final a las personas que no pueden ver aparecer el mensaje.

Anatomy

Grupo de campos
Una etiqueta, su control y su texto de ayuda o mensaje de error, agrupados para que el espaciado entre los tres se mantenga consistente en todos los campos.
Etiqueta
Un elemento label real con un atributo for que coincide con el id del input. Esto es lo que hace que la etiqueta sea clicable y lo que le da al input un nombre accesible.
Control
El input o textarea, que lleva un name para los datos del formulario, un type para el teclado móvil correcto y un token de autocomplete para el relleno del navegador.
Texto de ayuda
Texto de apoyo opcional conectado con aria-describedby, utilizado para cualquier cosa que de otro modo iría en un placeholder.
Mensaje de error
Reemplaza al texto de ayuda cuando un campo falla. También está conectado con aria-describedby y emparejado con aria-invalid en el control.
Botón de envío
Un botón de envío real para que Enter envíe el formulario. Deshabilitado durante el envío, con una etiqueta que refleja el estado actual.
Región de estado
Una live region educada que lleva el mensaje de éxito, para que la confirmación se anuncie en lugar de aparecer solo en pantalla.

How to Use

  1. 1

    Copiar el formulario

    Toma la versión HTML para confiar en la validación nativa del navegador, o la versión React para mensajes personalizados y un estado de envío controlado.

  2. 2

    Conecta tu endpoint

    Reemplaza la llamada fetch comentada con tu ruta de API, servicio de formulario o server action. Los datos del formulario ya se recopilan como un objeto FormData.

  3. 3

    Ajusta los campos

    Añade o elimina grupos de campos según sea necesario. Cada uno necesita un par coincidente de for en la label y id en el input - esa conexión es lo que hace que el campo sea usable.

  4. 4

    Configurar tokens de autocompletado

    Use the standard values: name, email, tel, organization. They are what let a browser fill the form in one tap on a phone.

  5. 5

    Handle the response

    Set the status to sent on success and surface a specific message on failure. A failed send that looks identical to a successful one is worse than an error.

Features

Real labels on every field

Each label is connected by id, making it clickable and giving the input an accessible name - not a placeholder doing the job badly.

Errors wired to their fields

Messages are connected through aria-describedby with aria-invalid on the control, so an error is announced when the field is focused rather than only visible.

Autocomplete support

Standard tokens on every field let browsers and password managers fill the form in one action, which is the difference between a tap and a paragraph of thumb typing.

Guarded submit

The button disables during sending and its label changes, preventing the double-click that sends duplicate messages.

Announced confirmation

The success message sits in a polite live region, so it reaches screen reader users instead of appearing silently.

Correct mobile keyboards

Input types are set per field, so an email field brings up a keyboard with an at sign rather than making people hunt for it.

Common Uses

Site contact pages

The standard name, email, and message form for general enquiries, where the goal is the fewest fields that still let you reply usefully.

Sales and demo requests

Extended with a company field and a subject select, routing enquiries without making the visitor guess which inbox to write to.

Support requests

Paired with a category select and an optional order or account reference, so the first reply can be useful rather than a request for details.

Feedback and bug reports

A message field with an optional email, where making the email optional meaningfully increases the number of reports received.

Accessibility

Customization

Props

PropTypeDefaultDescription
onSubmit(data: FormData) => Promise<void>-Se ejecuta con los datos del formulario una vez superada la validación. Mantén la llamada de red fuera del componente para que el mismo formulario pueda enviar a diferentes endpoints.
successMessagestring"Thanks - we will reply shortly."Anunciado a través de una live region educada tras un envío exitoso, para que la confirmación llegue tanto a usuarios de lectores de pantalla como a usuarios videntes.

Why Use These Formulario de contactos?

It gets the unglamorous parts right. Labels connected by id, autocomplete tokens, aria-describedby on errors, and a guarded submit are the difference between a form that works for everyone and one that works for whoever built it.

Validation runs on submit and clears per field, rather than flagging an email as invalid while it is still being typed - the behaviour that makes so many forms feel hostile.

Sin librería de formularios. Para tres campos, un validador de esquemas y un paquete de estado de formulario son más configuración que el formulario en sí, y aún así te dejan la implementación de accesibilidad a ti.

Tips

Frequently Asked Questions