Inputs

Email Typo Guard

An email field with two checks: the address shape first, then the domain — a typo like "gmial.com" is caught and fixed with one button.

  • input
  • email
  • validation
  • form

Preview

1440pxHost theme

Use it with AI

  1. 1. Copy the link.
  2. 2. Write to your agent in your own words and drop the link into the sentence.
  3. 3. The agent opens the link and installs the component from the registry.

put this in the header: https://vibeui.ru/c/input-006?lang=en

Проверим формат и домен, когда вы уйдёте из поля.

Show the full instructions

What the link says, spelled out. Use it when your agent cannot open links — paste this text instead.

# Install and place "input-006" (Email Typo Guard) from VibeUI

## 1. Install first — do not skip, do not recreate
Run this exact command before writing any code:
npx shadcn@latest add https://vibeui.ru/r/input-006.json

Registry item: https://vibeui.ru/r/input-006.json
Installs to: components/vibeui/input-006.tsx (the exact path follows this project's components.json aliases).
npm dependencies: none.
Registry dependencies: none.

Install it from the registry. Do not recreate it from the description,
do not substitute a similar component from another library, and do not
rewrite it to match the project's existing style.

## 2. What it is
An email field with two checks: the address shape first, then the domain — a typo like "gmial.com" is caught and fixed with one button.

An email field: shape checked on blur, domain typos found by Damerau–Levenshtein distance, and a "did you mean" button. Zero dependencies, one file, its own palette.

## 3. How to use it
import { Input006 } from "@/components/vibeui/input-006"

<Input006
  label="Work email"
  defaultValue="anna.orlova@gmial.com"
  onChange={(value) => setEmail(value)}
/>

Read the installed file for the full prop list.

## 4. Where to place it
This is a small inline component. Put it exactly where the user asked,
inside the existing markup. Do not create a new page, section or
wrapper for it. If a similar control already sits in that spot,
replace it instead of adding a second one.

Placement: ___
(The user fills this line in. If it is still blank, ask where to put it
instead of guessing.)

## 5. Keep exactly as installed
- the local --vibeui-input-006-* palette — do not swap it for your theme tokens (bg-muted, border-input and the like)
- checking on blur rather than on every keystroke: complaining about a half-typed address is unfair
- offering the fix as a button, not as text — a fix you only read still has to be retyped
- Damerau–Levenshtein instead of plain Levenshtein: swapping two letters in "gmial" must count as one edit
- type="email" and inputMode="email": that is the keyboard with @ and a dot on phones
- aria-invalid and aria-describedby: the shape message is read together with the value

## 6. You may change
- the label copy and the starting defaultValue
- the domains list — the common domains of your audience
- the wording of the hint and the error
- the accent through the accent prop

## 7. Rules
- A client check guarantees nothing: the address is still confirmed by email.
- Do not apply the fix automatically — a rare domain that resembles a common one would be lost silently.
- Keep domains short: every keystroke walks the whole list computing distances.
- Do not lift the CSS variables into globals.css: the component has to stay a single file.

## 8. Verify
- it renders with no console errors;
- it looks like the preview on the VibeUI page you copied this from;
- if it does not, you changed something listed in section 5 — put it back.

For developers

npx shadcn@latest add https://vibeui.ru/r/input-006.json
https://vibeui.ru/r/input-006.json

Компонент самодостаточен: один файл, без зависимостей, собственная палитра в локальных переменных --vibeui-input-006-*. Клиентский: "use client". Формат проверяется регулярным выражением по уходу из поля (состояние checked), домен сравнивается с частыми через расстояние Дамерау — Левенштейна: перестановка соседних букв считается одной правкой, поэтому «gmial» находится как опечатка «gmail». Исправление предлагается настоящей кнопкой, которая подставляет адрес целиком. Состояние живёт на внутреннем [data-part="body"], от него красится рамка и значок.

Component source

The same file your agent installs. Here in case you would rather copy it by hand.

"use client"

import { useId, useState } from "react"
import type { ComponentPropsWithoutRef, CSSProperties } from "react"

export type Input006Props = Omit<
  ComponentPropsWithoutRef<"div">,
  "children" | "defaultValue" | "onChange"
> & {
  label?: string
  defaultValue?: string
  domains?: string[]
  onChange?: (value: string) => void
  accent?: string
}

// Идея компонента: почту чаще всего ломает не формат, а опечатка в домене —
// «gmial.com» проходит любую регулярку и молча теряет письмо. Поле сначала
// проверяет форму адреса, а потом сравнивает домен с частыми и предлагает
// исправление одной кнопкой. Проверка включается по уходу из поля: ругаться
// на недописанный адрес нечестно.
const STYLES = `
:where([data-vibeui-block="input-006"]){
--vibeui-input-006-surface:oklch(1 0 0);
--vibeui-input-006-shell:oklch(0.91 0.006 265);
--vibeui-input-006-fg:oklch(0.23 0.014 265);
--vibeui-input-006-muted:oklch(0.55 0.014 265);
--vibeui-input-006-field:oklch(0.985 0.002 265);
--vibeui-input-006-border:oklch(0.88 0.008 265);
--vibeui-input-006-accent:oklch(0.55 0.19 262);
--vibeui-input-006-bad:oklch(0.55 0.2 25);
--vibeui-input-006-ok:oklch(0.5 0.13 155);
--vibeui-input-006-font:ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif;
}
/* Своя светлая подложка: поле показывают поверх произвольного фона. */
[data-vibeui-block="input-006"]{
display:flex;flex-direction:column;gap:0.4375rem;
width:100%;max-width:22rem;box-sizing:border-box;padding:0.875rem;
background:var(--vibeui-input-006-surface);
border:1px solid var(--vibeui-input-006-shell);border-radius:0.875rem;
font-family:var(--vibeui-input-006-font);color:var(--vibeui-input-006-fg);
}
[data-vibeui-block="input-006"] *{box-sizing:border-box}
[data-vibeui-block="input-006"] label{font-size:0.8125rem;font-weight:600}
[data-vibeui-block="input-006"] [data-part="frame"]{
display:flex;align-items:center;gap:0.5rem;
height:2.5rem;padding:0 0.75rem;
background:var(--vibeui-input-006-field);
border:1px solid var(--vibeui-input-006-border);border-radius:0.75rem;
transition:border-color .16s ease,box-shadow .16s ease;
}
[data-vibeui-block="input-006"] [data-part="frame"]:focus-within{
border-color:var(--vibeui-input-006-accent);
box-shadow:0 0 0 3px color-mix(in oklab,var(--vibeui-input-006-accent) 18%,transparent);
}
[data-vibeui-block="input-006"] [data-state="bad"] [data-part="frame"]{border-color:var(--vibeui-input-006-bad)}
[data-vibeui-block="input-006"] [data-state="ok"] [data-part="frame"]{border-color:var(--vibeui-input-006-ok)}
[data-vibeui-block="input-006"] [data-part="body"]{display:flex;flex-direction:column;gap:0.4375rem}
[data-vibeui-block="input-006"] input{
flex:1;min-width:0;height:100%;border:0;background:none;color:inherit;
font:inherit;font-size:0.875rem;
}
[data-vibeui-block="input-006"] input:focus{outline:none}
[data-vibeui-block="input-006"] [data-part="mark"]{
flex:none;width:1rem;height:1rem;display:grid;place-items:center;
}
[data-vibeui-block="input-006"] [data-part="mark"] svg{width:1rem;height:1rem;display:block}
[data-vibeui-block="input-006"] [data-state="ok"] [data-part="mark"]{color:var(--vibeui-input-006-ok)}
[data-vibeui-block="input-006"] [data-state="bad"] [data-part="mark"]{color:var(--vibeui-input-006-bad)}
[data-vibeui-block="input-006"] [data-part="note"]{
font-size:0.75rem;line-height:1.4;color:var(--vibeui-input-006-muted);margin:0;
}
[data-vibeui-block="input-006"] [data-part="note"][data-tone="bad"]{color:var(--vibeui-input-006-bad)}
/* Исправление — настоящая кнопка: подсказку «вы имели в виду» надо уметь
   принять одним нажатием, иначе её просто перечитывают и правят руками. */
[data-vibeui-block="input-006"] [data-part="fix"]{
appearance:none;cursor:pointer;text-align:left;
padding:0.4375rem 0.625rem;border-radius:0.625rem;
border:1px dashed color-mix(in oklab,var(--vibeui-input-006-accent) 45%,transparent);
background:color-mix(in oklab,var(--vibeui-input-006-accent) 8%,transparent);
color:inherit;font:inherit;font-size:0.75rem;line-height:1.4;
transition:background-color .16s ease;
}
[data-vibeui-block="input-006"] [data-part="fix"]:hover{
background:color-mix(in oklab,var(--vibeui-input-006-accent) 15%,transparent);
}
[data-vibeui-block="input-006"] [data-part="fix"]:focus-visible{
outline:2px solid var(--vibeui-input-006-accent);outline-offset:2px;
}
[data-vibeui-block="input-006"] [data-part="fix"] b{font-weight:650;color:var(--vibeui-input-006-accent)}
@media (prefers-reduced-motion:reduce){[data-vibeui-block="input-006"] *{animation:none!important;transition:none!important}}
`

const SHAPE = /^[^\s@]+@[^\s@.]+\.[^\s@]{2,}$/

// Расстояние Дамерау — Левенштейна: «gmial.com» отличается от «gmail.com»
// перестановкой соседних букв, а обычная Левенштейна считает её за две правки.
function distance(source: string, target: string) {
  const rows = Array.from({ length: source.length + 1 }, (_, index) =>
    Array.from({ length: target.length + 1 }, (_, column) =>
      index === 0 ? column : column === 0 ? index : 0,
    ),
  )

  for (let row = 1; row <= source.length; row += 1) {
    for (let column = 1; column <= target.length; column += 1) {
      const cost = source[row - 1] === target[column - 1] ? 0 : 1
      rows[row][column] = Math.min(
        rows[row - 1][column] + 1,
        rows[row][column - 1] + 1,
        rows[row - 1][column - 1] + cost,
      )

      if (
        row > 1 &&
        column > 1 &&
        source[row - 1] === target[column - 2] &&
        source[row - 2] === target[column - 1]
      ) {
        rows[row][column] = Math.min(
          rows[row][column],
          rows[row - 2][column - 2] + 1,
        )
      }
    }
  }

  return rows[source.length][target.length]
}

function suggest(value: string, domains: string[]) {
  const at = value.lastIndexOf("@")
  if (at < 1) return null

  const domain = value.slice(at + 1).toLowerCase()
  if (!domain || domains.includes(domain)) return null

  const near = domains.find((candidate) => distance(domain, candidate) <= 2)
  return near ? `${value.slice(0, at + 1)}${near}` : null
}

/**
 * Поле почты с проверкой формата и подсказкой при опечатке в домене.
 * Один файл, ноль зависимостей, собственная палитра.
 */
export function Input006({
  label = "Рабочая почта",
  defaultValue = "anna.orlova@gmial.com",
  domains = ["gmail.com", "yandex.ru", "mail.ru", "outlook.com", "icloud.com"],
  onChange,
  accent,
  className,
  style,
  ...props
}: Input006Props) {
  const id = useId()
  const [value, setValue] = useState(defaultValue)
  const [checked, setChecked] = useState(true)

  const palette = {
    ...(accent ? { "--vibeui-input-006-accent": accent } : null),
    ...style,
  } as CSSProperties

  const valid = SHAPE.test(value)
  const fix = valid ? suggest(value, domains) : null
  const state = !checked || !value ? "idle" : valid ? "ok" : "bad"

  const apply = (next: string) => {
    setValue(next)
    setChecked(true)
    onChange?.(next)
  }

  return (
    <>
      <style href="vibeui-input-006" precedence="medium">
        {STYLES}
      </style>
      <div
        {...props}
        data-vibeui-block="input-006"
        className={className}
        style={palette}
      >
        <label htmlFor={id}>{label}</label>
        <div data-part="body" data-state={state}>
          <div data-part="frame">
            <input
              id={id}
              type="email"
              inputMode="email"
              autoComplete="email"
              spellCheck={false}
              placeholder="name@company.com"
              value={value}
              aria-invalid={state === "bad"}
              aria-describedby={`${id}-note`}
              onChange={(event) => {
                setValue(event.target.value)
                setChecked(false)
                onChange?.(event.target.value)
              }}
              onBlur={() => setChecked(true)}
            />
            {state !== "idle" ? (
              <span data-part="mark" aria-hidden="true">
                {state === "ok" ? (
                  <svg
                    viewBox="0 0 16 16"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="2"
                  >
                    <path
                      d="M3.5 8.5 6.5 11.5 12.5 5"
                      strokeLinecap="round"
                      strokeLinejoin="round"
                    />
                  </svg>
                ) : (
                  <svg
                    viewBox="0 0 16 16"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="2"
                  >
                    <path d="M8 4.5v4.5" strokeLinecap="round" />
                    <circle
                      cx="8"
                      cy="11.75"
                      r="0.85"
                      fill="currentColor"
                      stroke="none"
                    />
                  </svg>
                )}
              </span>
            ) : null}
          </div>
          <p
            data-part="note"
            id={`${id}-note`}
            data-tone={state === "bad" ? "bad" : "calm"}
          >
            {state === "bad"
              ? "Адрес неполный: нужны имя, собака и домен."
              : "Проверим формат и домен, когда вы уйдёте из поля."}
          </p>
          {fix ? (
            <button type="button" data-part="fix" onClick={() => apply(fix)}>
              Возможно, вы имели в виду <b>{fix}</b>
            </button>
          ) : null}
        </div>
      </div>
    </>
  )
}