call(back)
FrontendmediumSign in to star problems

Six-Digit Code Input

Build a verification-code input: six single-digit fields with Submit and Reset. The default template is React, and an HTML/CSS/JS template is the alternate.

Requirements

  • Each field takes one digit, and anything else is ignored. Typing a digit moves focus to the next field.
  • Backspace in an empty field steps back to the previous field and clears it. In a filled field, it clears that digit.
  • ArrowLeft and ArrowRight move between fields.
  • Pasting a whole code into any field fills all six from the start, ignoring spaces and dashes.
  • Submit is enabled only when all six fields are filled. It calls verifyCode(code) from api.js, where 123456 is correct.
  • While the request is in flight, everything is disabled. Show the result: a success message, or the error, with the fields editable again.
  • Reset clears everything and puts focus back on the first field.
  • Label each field, such as "Digit 1 of 6", and use inputMode="numeric", plus autocomplete="one-time-code" on the first field.

Hints

Hint 1

Keep the six digits as one array in state, and the input elements in a ref array so you can call .focus() on a neighbor.

Hint 2

Handle paste yourself: read event.clipboardData.getData("text"), keep the digits, fill from the first field, and preventDefault so the browser doesn't insert the raw text.

Hint 3

Select a field's contents on focus. Typing then replaces the digit, and the newest digit wins wherever the caret was.

Asked at