Components Forms

Input OTP

Enter a one-time code on a monochrome verification ticket. Each digit has its own slot, and the whole code can be pasted at once.

Live previewGo + JavaScript

Type or paste your six-digit code.

Usage

Set Length to the number of digits you expect (six by default). Use Name for the form field, Required to require a code, and Disabled to turn off entry. Pass a string for Value to preserve leading zeroes.

Register input-otp with Head and pass its properties to Render. Go setup guide

Try pasting 012-345 into the preview. Codes up to 12 digits appear in individual slots, and longer codes use a single text box. Arrow keys, Backspace, and text selection work across the entire code. Supporting browsers can also suggest a code using autocomplete="one-time-code".

Inside a POST form, read r.PostFormValue("code") as a string and verify it on the server. Filling the last slot leaves submission to your form. With JavaScript disabled, visitors can still enter and submit the code in the labeled field.

Go usage
Go usage
err := mono.UI.Render(w, "input-otp", mono.Props{
	"Hint":     "Type or paste your six-digit code.",
	"Label":    "Verification code",
	"Length":   6,
	"Name":     "code",
	"Required": true,
})
Rendered HTML
Rendered HTML
<div id="demo-input-otp" class="mu-otp" data-mono="input-otp">
  <div class="mu-otp-pass">
    <div class="mu-otp-stub" aria-hidden="true">
      <svg class="mu-otp-print" width="108" height="125" viewBox="0 0 112 130" fill="none" focusable="false">
        <g stroke="currentColor" opacity=".48"><path d="M2 14V2h12m84 0h12v12M2 116v12h12m84 0h12v-12"/></g>
        <g stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
          <path d="M34 21c12-7 27-8 40-2M18 39c4-6 8-10 12-13m49-4c8 4 13 10 17 17"/>
          <path d="M12 56c4-17 14-29 29-34 20-7 42 1 53 17m4 6 3 8"/>
          <path d="M12 71c1-8 2-17 6-25 8-16 25-24 42-22 19 2 32 15 36 32"/>
          <path d="M14 80c5-10 3-20 8-31 7-15 22-22 37-20 17 2 30 14 33 30 1 7 1 13 5 18"/>
          <path d="M18 87c5-11 4-18 6-28 3-15 15-26 29-26 17-1 32 11 34 27 2 13 1 17 9 26"/>
          <path d="M20 94c9-11 7-24 10-37 3-12 13-20 25-20 15 0 26 11 28 25m0 8c1 9 5 16 10 21"/>
          <path d="M24 99c8-10 9-20 9-29 1-19 9-30 22-29 13 0 23 10 24 24 0 14 4 23 11 31"/>
          <path d="M29 102c6-8 9-18 9-28 0-17 4-28 16-29 11-1 20 9 21 22 0 17 4 22 12 33"/>
          <path d="M34 106c6-8 9-20 9-32 0-15 3-24 12-25 9 0 15 8 15 19 0 16 4 26 12 36"/>
          <path d="M39 108c5-8 8-18 8-28m0-6c0-12 2-20 8-21 7 0 11 7 11 16 0 16 4 28 12 38"/>
          <path d="M45 111c5-10 7-21 6-32 0-13 0-21 5-21 4 0 6 5 6 11-1 17 2 29 11 41"/>
          <path d="M51 113c4-10 5-19 5-27m0-7c0-6-1-11 0-15m1 30c1 6 3 13 6 18"/>
          <path d="M60 83c0 10 3 20 8 29"/>
        </g>
      </svg>
    </div>
    <div class="mu-otp-body">
      <label class="mu-otp-label" for="demo-input-otp-code">Verification code</label>
      <p class="mu-otp-hint" id="demo-input-otp-hint">Type or paste your six-digit code.</p>
      <div class="mu-otp-entry" dir="ltr">
        <div class="mu-otp-slots" data-otp-slots hidden aria-hidden="true"></div>
        <input id="demo-input-otp-code" class="mu-otp-input" data-otp-input
          name="code" type="text" dir="ltr" inputmode="numeric" autocomplete="one-time-code"
          minlength="6" maxlength="6" pattern="[0-9]{6}"
          value="" aria-describedby="demo-input-otp-hint" required >
      </div>
      <div class="mu-otp-footer">
        <span class="mu-otp-status" data-otp-status hidden></span>
        <span class="mu-otp-track" aria-hidden="true"><span data-otp-meter></span></span>
      </div>
    </div>
  </div>
</div>
Go template
Go template
<div id="{{.ID}}" class="mu-otp" data-mono="input-otp">
  <div class="mu-otp-pass">
    <div class="mu-otp-stub" aria-hidden="true">
      <svg class="mu-otp-print" width="108" height="125" viewBox="0 0 112 130" fill="none" focusable="false">
        <g stroke="currentColor" opacity=".48"><path d="M2 14V2h12m84 0h12v12M2 116v12h12m84 0h12v-12"/></g>
        <g stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
          <path d="M34 21c12-7 27-8 40-2M18 39c4-6 8-10 12-13m49-4c8 4 13 10 17 17"/>
          <path d="M12 56c4-17 14-29 29-34 20-7 42 1 53 17m4 6 3 8"/>
          <path d="M12 71c1-8 2-17 6-25 8-16 25-24 42-22 19 2 32 15 36 32"/>
          <path d="M14 80c5-10 3-20 8-31 7-15 22-22 37-20 17 2 30 14 33 30 1 7 1 13 5 18"/>
          <path d="M18 87c5-11 4-18 6-28 3-15 15-26 29-26 17-1 32 11 34 27 2 13 1 17 9 26"/>
          <path d="M20 94c9-11 7-24 10-37 3-12 13-20 25-20 15 0 26 11 28 25m0 8c1 9 5 16 10 21"/>
          <path d="M24 99c8-10 9-20 9-29 1-19 9-30 22-29 13 0 23 10 24 24 0 14 4 23 11 31"/>
          <path d="M29 102c6-8 9-18 9-28 0-17 4-28 16-29 11-1 20 9 21 22 0 17 4 22 12 33"/>
          <path d="M34 106c6-8 9-20 9-32 0-15 3-24 12-25 9 0 15 8 15 19 0 16 4 26 12 36"/>
          <path d="M39 108c5-8 8-18 8-28m0-6c0-12 2-20 8-21 7 0 11 7 11 16 0 16 4 28 12 38"/>
          <path d="M45 111c5-10 7-21 6-32 0-13 0-21 5-21 4 0 6 5 6 11-1 17 2 29 11 41"/>
          <path d="M51 113c4-10 5-19 5-27m0-7c0-6-1-11 0-15m1 30c1 6 3 13 6 18"/>
          <path d="M60 83c0 10 3 20 8 29"/>
        </g>
      </svg>
    </div>
    <div class="mu-otp-body">
      <label class="mu-otp-label" for="{{.ID}}-code">{{or .Label "Verification code"}}</label>
      {{with .Hint}}<p class="mu-otp-hint" id="{{$.ID}}-hint">{{.}}</p>{{end}}
      <div class="mu-otp-entry" dir="ltr">
        <div class="mu-otp-slots" data-otp-slots hidden aria-hidden="true"></div>
        <input id="{{.ID}}-code" class="mu-otp-input" data-otp-input
          name="{{or .Name .ID}}" type="text" dir="ltr" inputmode="numeric" autocomplete="one-time-code"
          minlength="{{or .Length 6}}" maxlength="{{or .Length 6}}" pattern="[0-9]{ {{- or .Length 6 -}} }"
          value="{{.Value}}" {{if .Hint}}aria-describedby="{{.ID}}-hint"{{end}} {{if .Required}}required{{end}} {{if .Disabled}}disabled{{end}}>
      </div>
      <div class="mu-otp-footer">
        <span class="mu-otp-status" data-otp-status hidden></span>
        <span class="mu-otp-track" aria-hidden="true"><span data-otp-meter></span></span>
      </div>
    </div>
  </div>
</div>
Component CSS
Component CSS
.mu-otp[data-mono] {
  --otp-paper: #fff;
  --otp-ink: #171717;
  --otp-muted: #5d5d5d;
  --otp-rule: #d3d3d3;
  --otp-key: #f7f7f7;
  --otp-stub-ink: #f5f5f5;
  --otp-stub-paper: #181818;
  container-type: inline-size;
  width: 100%;
  max-width: 42rem;
  color: var(--otp-ink);
}
[data-theme="dark"] .mu-otp[data-mono] {
  --otp-paper: #242424;
  --otp-ink: #f4f4f4;
  --otp-muted: #bababa;
  --otp-rule: #555;
  --otp-key: #303030;
  --otp-stub-paper: #0f0f0f;
  color-scheme: dark;
}
.mu-otp-pass {
  --otp-stub: 23%;
  --otp-notch: .42rem;
  display: grid;
  grid-template-columns: var(--otp-stub) minmax(0, 1fr);
  overflow: hidden;
  border: 1px solid var(--otp-rule);
  border-radius: .68rem;
  background: var(--otp-paper);
  mask: radial-gradient(circle at var(--otp-stub) 0, transparent var(--otp-notch), #000 calc(var(--otp-notch) + .7px)),
        radial-gradient(circle at var(--otp-stub) 100%, transparent var(--otp-notch), #000 calc(var(--otp-notch) + .7px));
  mask-composite: intersect;
}
.mu-otp-stub {
  position: relative;
  display: grid;
  place-items: center;
  min-width: 0;
  padding: .8rem;
  color: var(--otp-stub-ink);
  background: radial-gradient(#424242 .6px, transparent .85px) 1px 1px / 8px 8px, var(--otp-stub-paper);
}
.mu-otp-stub::after {
  content: "";
  position: absolute;
  inset: .62rem .2rem .62rem auto;
  width: 1px;
  background: repeating-linear-gradient(to bottom, #979797 0 3px, transparent 3px 7px);
}
.mu-otp-print { display: block; width: min(100%, 6.75rem); height: auto; }
.mu-otp-body {
  min-width: 0;
  padding: clamp(1.15rem, 5cqi, 2.15rem) clamp(1rem, 5.2cqi, 2.4rem);
}
.mu-otp-label {
  display: block;
  width: fit-content;
  color: var(--otp-ink);
  font: 500 clamp(1.8rem, 6.5cqi, 2.7rem)/1.06 "Iowan Old Style", "Palatino Linotype", Georgia, serif;
  letter-spacing: -.055em;
  overflow-wrap: anywhere;
}
.mu-otp-hint {
  margin: .56rem 0 0;
  color: var(--otp-muted);
  font-size: clamp(.85rem, 2.3cqi, .95rem);
  line-height: 1.45;
}
.mu-otp-entry { position: relative; width: 100%; margin-top: clamp(1.1rem, 3.8cqi, 1.65rem); }
.mu-otp[data-otp-enhanced] .mu-otp-entry { max-width: calc(var(--otp-count) * 4.7rem); }
.mu-otp-input {
  width: 100%;
  min-width: 0;
  padding: .55rem .72rem;
  border: 1px solid var(--otp-rule);
  border-radius: .35rem;
  background: var(--otp-key);
  color: var(--otp-ink);
  font: 600 1.4rem/1.5 ui-monospace, monospace;
  letter-spacing: .2em;
}
.mu-otp-input:focus-visible { outline: 2px solid var(--otp-ink); outline-offset: 2px; }
.mu-otp-slots {
  --otp-gap: clamp(.22rem, 1.25cqi, .5rem);
  display: flex;
  gap: var(--otp-gap);
  width: 100%;
}
.mu-otp-slots > span {
  position: relative;
  display: grid;
  flex: 1 1 0;
  place-items: center;
  min-width: 0;
  height: clamp(2.65rem, 10.5cqi, 3.8rem);
  border: 1px solid var(--otp-rule);
  border-radius: .35rem;
  background: var(--otp-key);
  color: var(--otp-ink);
  font: 500 clamp(1.2rem, 4.9cqi, 2rem)/1 ui-monospace, "SFMono-Regular", Consolas, monospace;
  font-variant-numeric: tabular-nums;
  transition: color .14s ease, background-color .14s ease, border-color .14s ease;
}
.mu-otp-slots > [data-gap] { margin-left: clamp(.35rem, 1.4cqi, .65rem); }
.mu-otp-slots > [data-gap]::before {
  content: "";
  position: absolute;
  right: calc(100% + var(--otp-gap) / 2);
  top: 50%;
  width: clamp(.25rem, .9cqi, .38rem);
  height: 1px;
  background: var(--otp-muted);
}
.mu-otp-slots > span:empty::after {
  content: "";
  width: .26rem;
  height: .26rem;
  border-radius: 50%;
  background: var(--otp-muted);
}
.mu-otp-slots > [data-filled] { background: var(--otp-paper); border-color: var(--otp-muted); }
.mu-otp-slots > :is([data-active],[data-selected]) {
  border-color: var(--otp-ink);
  background: var(--otp-ink);
  color: var(--otp-paper);
}
.mu-otp-slots > [data-active]:empty::after {
  width: 2px;
  height: .93em;
  border-radius: 1px;
  background: currentColor;
  animation: mu-otp-caret 1.2s ease-in-out infinite alternate;
}
@keyframes mu-otp-caret { to { opacity: .42; } }
.mu-otp[data-otp-enhanced] .mu-otp-input {
  position: absolute;
  z-index: 1;
  inset: 0;
  height: 100%;
  margin: 0;
  padding: 0;
  border: 0;
  opacity: 0;
  cursor: text;
  font-size: 16px;
}
.mu-otp[data-invalid] .mu-otp-slots > span { border-style: dashed; border-color: var(--otp-ink); }
.mu-otp-entry:has(.mu-otp-input:focus-visible) .mu-otp-slots { outline: 2px solid var(--otp-ink); outline-offset: 3px; border-radius: .35rem; }
.mu-otp:not([data-otp-enhanced]) .mu-otp-footer { display: none; }
.mu-otp-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: .75rem;
  margin-top: 1.05rem;
  padding-top: .72rem;
  border-top: 1px solid var(--otp-rule);
}
.mu-otp-status { color: var(--otp-muted); font: 500 .72rem/1.45 ui-monospace, "SFMono-Regular", Consolas, monospace; }
.mu-otp[data-complete] .mu-otp-status, .mu-otp[data-invalid] .mu-otp-status { color: var(--otp-ink); }
.mu-otp-track { display: block; flex: 0 1 3.8rem; height: 3px; overflow: hidden; border-radius: 3px; background: var(--otp-rule); }
.mu-otp-track > span { display: block; height: 100%; width: var(--otp-progress, 0%); background: var(--otp-ink); transition: width .16s ease-out; }
.mu-otp:has(.mu-otp-input:disabled) .mu-otp-entry { opacity: .55; }
.mu-otp:has(.mu-otp-input:disabled) .mu-otp-input { cursor: not-allowed; }
.mu-otp[data-compact] .mu-otp-slots { --otp-gap: .15rem; }
.mu-otp[data-compact] .mu-otp-slots > span { font-size: clamp(.85rem, 3.25cqi, 1.45rem); }
@container (max-width: 27rem) {
  .mu-otp-pass { --otp-stub: 16%; --otp-notch: .32rem; }
  .mu-otp-stub { padding: .45rem; }
  .mu-otp-body { padding: 1rem .85rem; }
  .mu-otp-label { font-size: clamp(1.5rem, 7.5cqi, 1.9rem); }
  .mu-otp-footer { margin-top: .85rem; padding-top: .6rem; }
}
@container (max-width: 19rem) {
  .mu-otp-pass { --otp-stub: 13%; }
  .mu-otp-stub { padding: .3rem; }
  .mu-otp-body { padding: .9rem .65rem; }
  .mu-otp-slots { --otp-gap: .18rem; }
}
@media (prefers-reduced-motion: reduce) {
  .mu-otp-slots > span, .mu-otp-track > span { transition: none; }
  .mu-otp-slots > [data-active]:empty::after { animation: none; }
}
@media (forced-colors: active) {
  .mu-otp-pass { border-color: CanvasText; }
  .mu-otp-stub { border-right: 1px dashed CanvasText; }
  .mu-otp-slots > [data-active] { outline: 2px solid Highlight; }
  .mu-otp-slots > [data-selected] { border: 2px dashed Highlight; }
  .mu-otp-slots > span:empty::after, .mu-otp-track > span { background: CanvasText; }
}
JavaScript module
JavaScript module
// The native text input owns the code, focus, selection, validation and form value.
// Slots only mirror it, so autofill and assistive technology use one field.
export function mount(root) {
  const input = root.querySelector('[data-otp-input]');
  const slots = root.querySelector('[data-otp-slots]');
  const status = root.querySelector('[data-otp-status]');
  const length = input?.maxLength;
  if (!slots || !input || length < 1 || length > 12 || root.hasAttribute('data-otp-enhanced')) return;

  const digits = text => text.replace(/[^0-9]/g, '');
  // Let the native field display an existing invalid draft without changing it.
  if (digits(input.value) !== input.value || input.value.length > length) return;

  const cells = Array.from({length}, (_, index) => {
    const cell = root.ownerDocument.createElement('span');
    cell.setAttribute('data-otp-slot', '');
    if ((length === 6 || length === 8) && index === length / 2) cell.setAttribute('data-gap', '');
    return cell;
  });
  slots.replaceChildren(...cells);
  slots.hidden = false;
  if (status) status.hidden = false;
  root.style.setProperty('--otp-count', length);
  root.toggleAttribute('data-compact', length > 8);
  root.setAttribute('data-otp-enhanced', '');

  let showErrors = false;
  let pasted = false;
  function render() {
    const value = input.value;
    const start = input.selectionStart;
    const end = input.selectionEnd;
    const focused = input.matches(':focus');
    const complete = value.length === length && digits(value) === value;
    const invalid = showErrors && !input.validity.valid;
    root.toggleAttribute('data-complete', complete);
    root.toggleAttribute('data-invalid', invalid);
    if (invalid) input.setAttribute('aria-invalid', 'true');
    else input.removeAttribute('aria-invalid');
    root.style.setProperty('--otp-progress', (100 * value.length / length) + '%');
    let label = complete ? 'Code entered' : value.length + ' of ' + length + ' digits';
    if (invalid) label = input.validity.customError ? input.validationMessage : 'Enter all ' + length + ' digits';
    if (status && status.textContent !== label) status.textContent = label;
    cells.forEach((cell, index) => {
      const digit = value[index] || '';
      if (cell.textContent !== digit) cell.textContent = digit;
      cell.toggleAttribute('data-filled', Boolean(digit));
      cell.toggleAttribute('data-selected', focused && index >= start && index < end);
      cell.toggleAttribute('data-active', focused && start === end && index === Math.min(start, length - 1));
    });
  }

  function normalize() {
    const value = input.value;
    const clean = digits(value).slice(0, length);
    if (clean !== value) {
      const position = digits(value.slice(0, input.selectionStart)).length;
      input.value = clean;
      input.setSelectionRange(position, position);
    }
    render();
  }
  input.addEventListener('beforeinput', event => {
    if (!event.isComposing && event.inputType === 'insertText' && event.data && !digits(event.data)) event.preventDefault();
  });
  input.addEventListener('input', event => { if (!event.isComposing) normalize(); });
  input.addEventListener('compositionend', normalize);
  input.addEventListener('paste', event => {
    if (!event.clipboardData || input.readOnly || input.matches(':disabled')) return;
    const text = event.clipboardData.getData('text/plain');
    const clean = digits(text);
    const wholeCode = clean.length === length;
    const start = wholeCode ? 0 : input.selectionStart;
    const end = wholeCode ? input.value.length : input.selectionEnd;
    if (clean === text && start === input.selectionStart && end === input.selectionEnd) return;
    event.preventDefault();
    const insert = clean.slice(0, length - input.value.length + end - start);
    if (!insert) return;
    input.setRangeText(insert, start, end, 'end');
    pasted = true;
    input.dispatchEvent(new Event('input', {bubbles: true}));
  });

  function indexAt(x) {
    let index = 0;
    let best = Infinity;
    cells.forEach((cell, i) => {
      const rect = cell.getBoundingClientRect();
      const distance = Math.abs(x - rect.left - rect.width / 2);
      if (distance < best) { index = i; best = distance; }
    });
    return Math.min(index, input.value.length);
  }
  function selectCells(first, last) {
    const start = Math.min(first, last);
    const end = Math.min(input.value.length, Math.max(first, last) + 1);
    input.setSelectionRange(start, end, first > last ? 'backward' : 'forward');
    render();
  }
  let anchor = null;
  let pointerType = '';
  input.addEventListener('pointerdown', event => {
    pointerType = event.pointerType;
    if (event.pointerType !== 'mouse' || event.button !== 0 || input.matches(':disabled')) return;
    event.preventDefault();
    input.focus();
    const index = indexAt(event.clientX);
    anchor = event.shiftKey ? input.selectionStart : index;
    input.setPointerCapture(event.pointerId);
    selectCells(anchor, index);
  });
  input.addEventListener('pointermove', event => {
    if (anchor !== null && input.hasPointerCapture(event.pointerId)) selectCells(anchor, indexAt(event.clientX));
  });
  input.addEventListener('lostpointercapture', () => { anchor = null; });
  input.addEventListener('click', event => {
    if (event.detail > 1) input.select();
    else if (event.detail && pointerType !== 'mouse' && !event.shiftKey) {
      const index = indexAt(event.clientX);
      selectCells(index, index);
    }
  });
  for (const event of ['focus', 'keyup', 'select', 'selectionchange']) input.addEventListener(event, render);
  input.addEventListener('change', () => { pasted = false; normalize(); });
  input.addEventListener('blur', () => {
    if (pasted) input.dispatchEvent(new Event('change', {bubbles: true}));
    if (input.value) showErrors = true;
    render();
  });
  input.addEventListener('invalid', () => { showErrors = true; render(); });
  input.form?.addEventListener('reset', event => setTimeout(() => {
    if (event.defaultPrevented) return;
    pasted = showErrors = false;
    render();
  }, 0));
  render();
}
Use the HTML in a static site

Copy the rendered HTML above. Download these assets into the same folder as your page, then add the tags below to its head.

Shared CSS Component CSS Ready-to-use module

HTML head
<link rel="stylesheet" href="./base.css">
<link rel="stylesheet" href="./input-otp.css">
<script type="module" src="./input-otp.js"></script>

Copy into your project

Run this command from the Mono checkout. Set -out to the component directory in your application.

Terminal
go run ./cmd/mono-ui add -out ./components input-otp
Example properties (JSON)
example.json
{
  "Hint": "Type or paste your six-digit code.",
  "Label": "Verification code",
  "Length": 6,
  "Name": "code",
  "Required": true
}