Skip to content
Tutorials Center
My learning

Topics

Lesson 138 of 156 ยท Projects

Project: Password Strength Meter and OTP Input

Build a live password strength meter with a rules checklist and a six-box one-time-code input that auto-advances, handles backspace and accepts pasted codes.

Two small widgets show up in almost every sign-up and login flow. The first is a password strength meter: as you type, a bar fills and a checklist tells you what is still missing. The second is a one-time-code (OTP) input: six little boxes where each digit lands in its own cell, the cursor jumps ahead by itself, and pasting a whole code from a text message fills every box at once.

Both look like decoration, yet they are full of small decisions that make forms feel good or feel broken. In this project you will build each one in two steps: first the logic as plain functions you can test in the console, then the interface that calls them. The pure functions come first on purpose: logic with no DOM is easy to test, and the screen stays a thin layer on top.

It builds on Validation Recipes, Events, Bubbling, Capturing and Delegation and Custom Events and Event Emitters.

A strength meter is feedback for the person typing, not a security gate. Real validation, hashing and rate limiting must happen on the server. A browser check can always be bypassed.

Part 1: The password strength meter

Step 1: Scoring a password

What makes a password strong? Mostly length, then variety, then not being predictable. We will award points for each, subtract points for known weak patterns, and map the total onto five levels.

Our rules:

  • One point for 8 or more characters, a second for 12 or more, a third for 16 or more.
  • One point for mixing character classes: lowercase, uppercase, digits and symbols (at least three of the four).
  • A hard cap at "very weak" for the most common passwords, whatever else they contain.
  • A penalty for obvious patterns: the same character repeated (aaaaaa), or a run such as abcd or 1234.

The function returns an object, not just a number, so the interface can show a label, a bar and a list of tips from one call.

JS Step 1: Scoring function

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Look at the results: sunshine1 is only "Weak" because it is short and has two character classes, while the long passphrase correct-horse-battery-staple reaches "Good" even though it has no digits or capitals, because length carries it. Only the long passphrase that also mixes classes (Correct-Horse-Battery-9!) earns "Strong". That matches current guidance: long and unpredictable beats short and complicated. abcd1234Zx has three character classes but two obvious runs, so the penalties pull it down.

Good estimators such as the open-source zxcvbn model dictionary words, keyboard patterns, names and dates. Our rules are deliberately simple so you can read every line. If you need real accuracy, use a maintained library, and consider checking against a breached-password service on the server.

Step 2: The live meter

Now the interface. The pieces are:

  • A type="password" input with autocomplete="new-password", so password managers know to offer a generated password.
  • A meter bar whose width and colour come from the score, using a data-score attribute so CSS does the styling.
  • A checklist, where each item toggles a "met" state.
  • A role="status" line (a polite live region) that announces the label to screen reader users, but only when the level changes, so it doesn't chatter on every keystroke.

The input event fires on every change, including paste and autofill, so that is the one to listen to.

Step 2: Live strength meter

Type password, then Password1, then Password1!x, and finally a long phrase, and watch the bar and checklist react. Three details are worth noticing:

  • data-score drives the look. JavaScript only writes one attribute; the colours and widths live in CSS selectors. Changing the design never touches the logic.
  • The live region only speaks on changes. The lastScore variable stops the verdict text from being rewritten on every keystroke, which would make a screen reader repeat itself.
  • The checklist uses classList.toggle(name, force). The second argument makes the call idempotent: "set this class to exactly this boolean", with no if/else.

Try adding a "Show password" checkbox that flips input.type between "password" and "text". Five Mini DOM Apps walks through it with the accessibility details.

Part 2: The OTP input

A one-time code (the six digits from a text message or an authenticator app) is short, so splitting it into boxes makes it easy to read and check. But six separate inputs create real work: you have to move focus yourself, handle deleting, and make pasting feel natural. Without that work, the widget is worse than one plain text field.

Here is what a good OTP input does:

  1. Accepts digits only, and ignores everything else.
  2. Advances to the next box after each digit.
  3. Backspace on an empty box deletes the previous digit and moves back.
  4. Arrow keys move between boxes.
  5. Paste spreads the digits over the boxes, starting wherever you pasted.
  6. Announces completion once all six are filled, so the page can verify the code.

Step 3: The logic first

Pasting is the tricky one, so isolate it as a pure function. Given the current six values, a start position and the pasted text, it returns the new values and where the cursor should go.

JS Step 3: Pure OTP helpers

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The function never touches the page, so we can check every edge case in one run: spaces and dashes are stripped, letters give an empty paste, and extra digits fall off the end. Writing the focus index into the result keeps focus logic in one place, too.

Step 4: The interface

The boxes are plain <input> elements. These attributes matter:

  • inputmode="numeric" shows a number pad on phones, while keeping the field a text input (so leading zeros survive; type="number" would strip them and add spinners).
  • autocomplete="one-time-code" on the first box lets Safari and Android offer the code from an incoming SMS.
  • maxlength="1" stops typing a second character, but a paste can still be handled, because we read it from the paste event ourselves and call preventDefault().
  • Each box has its own aria-label ("Digit 1 of 6"), because there are no visible labels.

We use event delegation: one listener on the wrapper handles all six boxes, and [...boxes].indexOf(event.target) tells us which one it was.

Step 4: Six-box code input

Click the first box and type a few digits, then press Backspace more times than you typed. Paste 482913 (copy it from the hint first) and watch every box fill and turn green. A few things in the code are worth studying:

  • slice(-1) keeps the newest digit. If a box already holds 4 and you type 7, the browser blocks it because of maxlength. On some mobile keyboards or when text is selected, though, the value can briefly hold two characters; taking the last one is the forgiving choice.
  • Backspace is handled on keydown, not input. An empty box has nothing to delete, so no input event fires. Catching the key itself is the only way to move back.
  • preventDefault() on paste. The browser would otherwise try to insert the whole string into one box and truncate it. We read the clipboard text from the event (allowed on a real paste gesture, unlike the standalone clipboard API) and distribute it ourselves.
  • Completion is checked in refresh(). Every path (typing, deleting, pasting) funnels through one function, so the checking logic exists exactly once.

For a one-box alternative, a single <input maxlength="6" inputmode="numeric" autocomplete="one-time-code"> styled with wide letter-spacing is often more accessible and gets SMS autofill for free. The multi-box version looks nicer; choose it knowingly.

Ideas to extend it

  • Resend countdown. Disable a "Send again" button for 30 seconds and show the remaining time. The clock project shows how to drive timers without drift.
  • Auto-submit. Dispatch a new CustomEvent("otp-complete", { detail: { code } }) from the wrapper and let the page listen, as described in Custom Events.
  • Breached-password check. On the server, compare a hash prefix against a breach list; give the user the result in the meter.
  • Strength by estimated guesses. Replace assess() with a dictionary-aware library and keep the same return shape so the interface does not change.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is a browser-side password strength meter not a security control?

    The meter is feedback for the person typing. Code in the page can be skipped or edited, so enforcement, hashing and rate limiting belong on the server.
  2. 2. Which password is generally best according to the scoring in this lesson, and why?

    Length carries the score. Short passwords with symbols are easy to guess, repeated characters and runs are penalised, and a long passphrase scores far higher than short complexity.
  3. 3. Why does the OTP widget handle Backspace in a keydown listener?

    Deleting from an empty field changes nothing, so the browser fires no input event. Listening for the key lets you move focus to the previous box and clear it.
  4. 4. What is the reason for calling event.preventDefault() in the paste handler?

    By default the browser inserts the pasted text into the focused field and truncates it. Cancelling that default lets you read clipboardData and fill one digit per box.
  5. 5. Which input attributes give the best mobile experience for a one-time code?

    inputmode="numeric" shows a number pad without the drawbacks of type="number" (lost leading zeros, spinners), and autocomplete="one-time-code" lets the OS offer the code from an SMS.

Summary

  • Separate logic from interface: assess() and applyPaste() are pure functions you can test in the console; the page just calls them.
  • A strength score rewards length most, then variety, and penalises repeats, runs and common passwords. It is feedback, never enforcement.
  • Drive the visuals with a data-score attribute and classList.toggle(name, force), so CSS owns the design.
  • Announce changes politely with role="status", and only when the level actually changes.
  • An OTP input needs digit filtering, auto-advance, Backspace on keydown, arrow keys and a custom paste handler.
  • Use inputmode="numeric" and autocomplete="one-time-code"; use event delegation so one listener serves all boxes.

Next: Project: Digital and Analog Clock, Stopwatch.