{
    "id": "bhaskar/verification-code-input",
    "kind": "component",
    "title": "Verification Code Input",
    "summary": "Six-box one-time code field with paste, SMS autofill, auto-advance, backspace and arrow keys, an error shake and a resend timer.",
    "author": "Admin",
    "stars": 0,
    "url": "https://ownlyplans.com/bhaskar/verification-code-input/",
    "stack": [
        "CSS",
        "HTML",
        "JavaScript",
        "React"
    ],
    "tools": [
        "claude-code",
        "cursor",
        "lovable"
    ],
    "difficulty": "beginner",
    "license": "mit",
    "version": "1.0",
    "overview": "The code screen after sign-up or two-factor login, done properly. Typing moves to the next box, Backspace goes back, the arrow keys move between boxes, and pasting \"123 456\" (or letting the phone autofill the SMS code) fills every box at once. Only digits are accepted.\r\n\r\nWhen all six digits are in, it checks the code: a wrong code shakes the boxes and says so, a right one turns them green. The resend link counts down so people do not spam it. In the preview the right code is 123456. In the React version pass verify(code) that calls your API and resolves true or false.\r\n\r\nMIT License\r\n\r\nCopyright (c) 2026 OwnlyPlans\r\n\r\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\r\n\r\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.",
    "steps": [],
    "files": [],
    "install": "npx shadcn@latest add https://ownlyplans.com/r/bhaskar/verification-code-input.json",
    "how_to_use": "Use the component code (html, css, js, or react) directly, or run the install command.",
    "component": {
        "category": "Other",
        "html": "<!--\nMIT License\n\nCopyright (c) 2026 OwnlyPlans\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n-->\n<form class=\"otp\" id=\"otp\" novalidate>\n  <h3 class=\"otp-h\">Check your email</h3>\n  <p class=\"otp-sub\">We sent a 6-digit code to <b>sam@example.com</b></p>\n  <div class=\"otp-boxes\" role=\"group\" aria-label=\"Verification code\" id=\"otp-boxes\"></div>\n  <p class=\"otp-msg\" id=\"otp-msg\" role=\"status\" aria-live=\"polite\"></p>\n  <p class=\"otp-resend\">Didn't get it? <button type=\"button\" id=\"otp-resend\" disabled>Resend in 30s</button></p>\n</form>",
        "css": "/*\n * MIT License\n *\n * Copyright (c) 2026 OwnlyPlans\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n.otp{width:min(380px,100%);padding:22px;border:1px solid var(--line);border-radius:16px;background:var(--stage);text-align:center;color:var(--ink)}\n.otp-h{margin:0 0 4px;font-size:18px}\n.otp-sub{margin:0 0 16px;color:var(--muted);font-size:13.5px}\n.otp-sub b{color:var(--ink);font-weight:600}\n.otp-boxes{display:flex;justify-content:center;gap:8px}\n.otp-boxes input{width:44px;height:52px;padding:0;border:1.5px solid var(--line);border-radius:12px;background:transparent;color:var(--ink);font:600 22px/1 ui-monospace,SFMono-Regular,Menlo,monospace;text-align:center;caret-color:var(--accent);transition:border-color .15s,box-shadow .15s}\n.otp-boxes input:focus{outline:none;border-color:var(--accent);box-shadow:0 0 0 4px color-mix(in srgb,var(--accent) 20%,transparent)}\n.otp-boxes input:nth-child(3){margin-right:10px}\n.otp.is-bad input{border-color:#d93838}\n.otp.is-bad .otp-boxes{animation:otp-shake .4s}\n.otp.is-ok input{border-color:#18a978;background:color-mix(in srgb,#18a978 10%,transparent)}\n@keyframes otp-shake{20%,60%{transform:translateX(-6px)}40%,80%{transform:translateX(6px)}}\n@media (prefers-reduced-motion:reduce){.otp.is-bad .otp-boxes{animation:none}}\n.otp-msg{min-height:20px;margin:10px 0 0;font-size:13px;font-weight:600}\n.otp.is-bad .otp-msg{color:#d93838}.otp.is-ok .otp-msg{color:#13915f}\n.otp-resend{margin:6px 0 0;color:var(--muted);font-size:13px}\n.otp-resend button{padding:0;border:0;background:none;color:var(--accent);font:inherit;font-weight:600;cursor:pointer}\n.otp-resend button:disabled{color:var(--muted);cursor:default}\n@media (max-width:380px){.otp{padding:18px 12px}.otp-boxes{gap:6px}.otp-boxes input{width:38px;height:48px;font-size:20px}.otp-boxes input:nth-child(3){margin-right:6px}}",
        "js": "/*\n * MIT License\n *\n * Copyright (c) 2026 OwnlyPlans\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\nconst N=6,RIGHT='123456',form=document.getElementById('otp'),wrap=document.getElementById('otp-boxes'),msg=document.getElementById('otp-msg'),resend=document.getElementById('otp-resend');\nconst boxes=[...Array(N)].map((_,i)=>{const b=document.createElement('input');b.type='text';b.inputMode='numeric';b.setAttribute('aria-label','Digit '+(i+1)+' of '+N);if(i===0)b.autocomplete='one-time-code';wrap.appendChild(b);return b});\nconst code=()=>boxes.map(b=>b.value).join('');\nfunction fill(from,digits){digits.split('').slice(0,N-from).forEach((d,k)=>boxes[from+k].value=d);const next=Math.min(from+digits.length,N-1);boxes[next].focus();check()}\nfunction check(){form.classList.remove('is-bad','is-ok');msg.textContent='';const c=code();if(c.length<N)return;\n boxes.forEach(b=>b.disabled=true);msg.textContent='Checking…';\n setTimeout(()=>{boxes.forEach(b=>b.disabled=false);if(c===RIGHT){form.classList.add('is-ok');msg.textContent='Verified. Welcome aboard!';boxes.forEach(b=>b.readOnly=true)}\n  else{void form.offsetWidth;form.classList.add('is-bad');msg.textContent='That code is not right. Try again.';boxes.forEach(b=>b.value='');boxes[0].focus()}},450)}\nboxes.forEach((b,i)=>{\n b.addEventListener('input',()=>{const d=b.value.replace(/\\D/g,'');if(d.length>1){b.value='';fill(i,d);return}b.value=d;if(d&&i<N-1)boxes[i+1].focus();check()});\n b.addEventListener('keydown',e=>{if(e.key==='Backspace'&&!b.value&&i>0){e.preventDefault();boxes[i-1].value='';boxes[i-1].focus();check()}\n  else if(e.key==='ArrowLeft'&&i>0){e.preventDefault();boxes[i-1].focus()}else if(e.key==='ArrowRight'&&i<N-1){e.preventDefault();boxes[i+1].focus()}});\n b.addEventListener('paste',e=>{e.preventDefault();const d=(e.clipboardData.getData('text')||'').replace(/\\D/g,'');if(d)fill(i,d)});\n b.addEventListener('focus',()=>b.select())});\nlet left=30,timer;function tick(){resend.disabled=left>0;resend.textContent=left>0?'Resend in '+left+'s':'Resend code';if(left-->0)timer=setTimeout(tick,1000)}\nresend.addEventListener('click',()=>{msg.textContent='New code sent.';form.classList.remove('is-bad','is-ok');left=30;tick()});\nform.addEventListener('submit',e=>e.preventDefault());tick();",
        "react": "/*\n * MIT License\n *\n * Copyright (c) 2026 OwnlyPlans\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\"use client\";\nimport { useEffect, useRef, useState } from \"react\";\n\nconst css = `\n.otp{width:min(380px,100%);padding:22px;border:1px solid #d8deeb;border-radius:16px;background:#fff;text-align:center;color:#0b1020;font:14px/1.5 system-ui,sans-serif}\n.otp-boxes{display:flex;justify-content:center;gap:8px}\n.otp-boxes input{width:44px;height:52px;padding:0;border:1.5px solid #d8deeb;border-radius:12px;background:transparent;color:inherit;font:600 22px/1 ui-monospace,monospace;text-align:center;caret-color:#1659f5}\n.otp-boxes input:focus{outline:none;border-color:#1659f5;box-shadow:0 0 0 4px rgba(22,89,245,.2)}\n.otp-boxes input:nth-child(3){margin-right:10px}\n.otp.is-bad input{border-color:#d93838}.otp.is-bad .otp-boxes{animation:otp-shake .4s}\n.otp.is-ok input{border-color:#18a978;background:rgba(24,169,120,.1)}\n@keyframes otp-shake{20%,60%{transform:translateX(-6px)}40%,80%{transform:translateX(6px)}}\n@media (prefers-reduced-motion:reduce){.otp.is-bad .otp-boxes{animation:none}}\n.otp-msg{min-height:20px;margin:10px 0 0;font-size:13px;font-weight:600}\n.otp.is-bad .otp-msg{color:#d93838}.otp.is-ok .otp-msg{color:#13915f}\n.otp-resend{margin:6px 0 0;color:#5c627c;font-size:13px}\n.otp-resend button{padding:0;border:0;background:none;color:#1659f5;font:inherit;font-weight:600;cursor:pointer}\n.otp-resend button:disabled{color:#5c627c;cursor:default}`;\n\nexport function VerificationCodeInput({\n  length = 6,\n  verify,\n  onVerified,\n  onResend,\n  resendAfter = 30,\n}: {\n  length?: number;\n  /** Check the code with your API. Resolve true when it is right. */\n  verify: (code: string) => Promise<boolean>;\n  onVerified?: (code: string) => void;\n  onResend?: () => void;\n  resendAfter?: number;\n}) {\n  const [digits, setDigits] = useState<string[]>(() => Array(length).fill(\"\"));\n  const [state, setState] = useState<\"idle\" | \"checking\" | \"ok\" | \"bad\">(\"idle\");\n  const [msg, setMsg] = useState(\"\");\n  const [left, setLeft] = useState(resendAfter);\n  const refs = useRef<(HTMLInputElement | null)[]>([]);\n\n  useEffect(() => {\n    if (left <= 0) return;\n    const t = setTimeout(() => setLeft((s) => s - 1), 1000);\n    return () => clearTimeout(t);\n  }, [left]);\n\n  const focus = (i: number) => refs.current[Math.max(0, Math.min(length - 1, i))]?.focus();\n\n  const update = (next: string[]) => {\n    setDigits(next);\n    if (state === \"bad\") { setState(\"idle\"); setMsg(\"\"); }\n    const code = next.join(\"\");\n    if (code.length === length && next.every(Boolean)) {\n      setState(\"checking\"); setMsg(\"Checking…\");\n      verify(code)\n        .then((ok) => {\n          if (ok) { setState(\"ok\"); setMsg(\"Verified.\"); onVerified?.(code); }\n          else { setState(\"bad\"); setMsg(\"That code is not right. Try again.\"); setDigits(Array(length).fill(\"\")); focus(0); }\n        })\n        .catch(() => { setState(\"bad\"); setMsg(\"Could not check the code. Try again.\"); });\n    }\n  };\n\n  const fillFrom = (i: number, text: string) => {\n    const d = text.replace(/\\D/g, \"\").slice(0, length - i);\n    if (!d) return;\n    const next = [...digits];\n    d.split(\"\").forEach((c, k) => (next[i + k] = c));\n    update(next);\n    focus(i + d.length);\n  };\n\n  return (\n    <div className={`otp${state === \"bad\" ? \" is-bad\" : state === \"ok\" ? \" is-ok\" : \"\"}`}>\n      <style>{css}</style>\n      <div className=\"otp-boxes\" role=\"group\" aria-label=\"Verification code\">\n        {digits.map((v, i) => (\n          <input\n            key={i}\n            ref={(el) => { refs.current[i] = el; }}\n            value={v}\n            inputMode=\"numeric\"\n            autoComplete={i === 0 ? \"one-time-code\" : \"off\"}\n            maxLength={length}\n            aria-label={`Digit ${i + 1} of ${length}`}\n            disabled={state === \"checking\"}\n            readOnly={state === \"ok\"}\n            onFocus={(e) => e.target.select()}\n            onChange={(e) => {\n              const d = e.target.value.replace(/\\D/g, \"\");\n              if (d.length > 1) return fillFrom(i, d);\n              const next = [...digits]; next[i] = d; update(next);\n              if (d) focus(i + 1);\n            }}\n            onKeyDown={(e) => {\n              if (e.key === \"Backspace\" && !digits[i] && i > 0) { e.preventDefault(); const next = [...digits]; next[i - 1] = \"\"; update(next); focus(i - 1); }\n              else if (e.key === \"ArrowLeft\") { e.preventDefault(); focus(i - 1); }\n              else if (e.key === \"ArrowRight\") { e.preventDefault(); focus(i + 1); }\n            }}\n            onPaste={(e) => { e.preventDefault(); fillFrom(i, e.clipboardData.getData(\"text\")); }}\n          />\n        ))}\n      </div>\n      <p className=\"otp-msg\" role=\"status\" aria-live=\"polite\">{msg}</p>\n      <p className=\"otp-resend\">\n        Didn't get it?{\" \"}\n        <button type=\"button\" disabled={left > 0} onClick={() => { onResend?.(); setLeft(resendAfter); setMsg(\"New code sent.\"); setState(\"idle\"); }}>\n          {left > 0 ? `Resend in ${left}s` : \"Resend code\"}\n        </button>\n      </p>\n    </div>\n  );\n}\n\n/* Usage:\n   <VerificationCodeInput verify={async (code) => (await fetch(\"/api/verify\", { method: \"POST\", body: JSON.stringify({ code }) })).ok}\n     onVerified={() => router.push(\"/welcome\")} onResend={() => fetch(\"/api/resend\", { method: \"POST\" })} />\n*/",
        "dependencies": [],
        "install": "npx shadcn@latest add https://ownlyplans.com/r/bhaskar/verification-code-input.json",
        "licence_notice": "MIT License\n\nCopyright (c) 2026 OwnlyPlans\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE."
    }
}