日本語

React: Warn When Caps Lock Is On in a Password Field

​​React​Accessibility,Forms,Playwright,TypeScript

The password field on a login screen hides what you type behind "•", so if Caps Lock is on, you don't notice until you're told "the password is wrong." In React, reading e.getModifierState('CapsLock') in the keyboard and mouse events of an input tells you whether Caps Lock is on, so you can show a warning below the field.

Note

Test environment: Ubuntu 24.04, Node.js 22.23.4. I used react / react-dom 19.3.1, @types/react 19.3.0, TypeScript 7.0.2, and esbuild 0.28.2. I type-checked the .tsx files with tsc, then made a development build. The browser was Chromium 153, run with Playwright 1.63.0. I sent Caps Lock key presses with xdotool as X key input to Chromium opened on a virtual display (Xvfb). So the behavior of the Caps Lock key's own events is what I saw in Chromium on Linux (X11). I did not test Windows or macOS, Firefox or Safari, smartphone browsers, or actual screen reader announcements.

Clicking the password field and pressing Caps Lock shows a warning below the field saying Caps Lock is on. Typing neko makes the entered value NEKO. Clicking the username field clears the warning. Returning to the password field with Tab shows the warning again before anything is typed.
How the Caps Lock warning switches when entering and leaving the password field. The cursor, the click ring, the key display, the explanatory text at the top, the ⚠ symbol before the warning, and the entered value shown below were added for the GIF.

Read getModifierState and show a warning below the password field

Here is the whole component. The Caps Lock state is kept in the capsLock state, and while it is on, the warning text saying Caps Lock is on (the actual Japanese text is in the code below) is shown below the field.

tsx
import { useState, type KeyboardEvent, type MouseEvent } from 'react';

export function PasswordField() {
  const [password, setPassword] = useState('');
  const [capsLock, setCapsLock] = useState(false);

  // Re-read the Caps Lock state on key down, key up, and click
  function checkCapsLock(e: KeyboardEvent<HTMLInputElement> | MouseEvent<HTMLInputElement>) {
    setCapsLock(e.getModifierState('CapsLock'));
  }

  return (
    <div>
      <label htmlFor="password">パスワード</label>
      <input
        id="password"
        type="password"
        autoComplete="current-password"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
        onKeyDown={checkCapsLock}
        onKeyUp={checkCapsLock}
        onMouseDown={checkCapsLock}
        onBlur={() => setCapsLock(false)}
        aria-describedby={capsLock ? 'capslock-warning' : undefined}
      />
      <p id="capslock-warning" role="status">
        {capsLock ? 'Caps Lock がオンになっています' : ''}
      </p>
    </div>
  );
}

getModifierState is a method that returns true or false, depending on whether a modifier key such as Shift or Caps Lock was on at the moment the event occurred (MDN: KeyboardEvent.getModifierState). React's event objects have a method with the same name. It is described in the official docs under both keyboard event handlers and mouse event handlers. The type definitions in @types/react 19.3.0 also have getModifierState(key: ModifierKey): boolean on the keyboard, mouse, and touch event types. So checkCapsLock can remain one function and be passed to both onKeyDown and onMouseDown.

Because getModifierState is a method on the event object, this code re-reads it every time a key or mouse event reaches the password field. When the field loses focus (onBlur), the warning is cleared.

autoComplete="current-password" tells browsers and password managers that this field is for entering the current password at login (MDN: allowing autocomplete on password fields).

Confirm when the warning appears with the real Caps Lock key

In the test environment, I pressed "a", Caps Lock, "b", Caps Lock, and "c" in order in the password field. The entered text became "aBc", and the warning changed as follows. The label for the X server's caps lock state (written in Japanese in the log below) is the state as seen with xset q. Items such as aria-describedby and the first click on the password field are omitted, and values are written only where they changed.

text
[a を押す] Xのキャップスロック=off 警告=なし 値="a"
[Caps Lock キーを押してオンにする] Xのキャップスロック=on 警告=「Caps Lock がオンになっています」
[b を押す] Xのキャップスロック=on 警告=「Caps Lock がオンになっています」 値="aB"
[Caps Lock キーを押してオフにする] Xのキャップスロック=off 警告=「Caps Lock がオンになっています」
[c を押す] Xのキャップスロック=off 警告=なし 値="aBc"

Pressing Caps Lock to turn it on showed the warning right away. Pressing it again to turn it off kept the warning, which disappeared when I pressed "c" next.

When I logged the value of getModifierState('CapsLock') for each event that reached the input, the reason was clear.

text
Caps Lock キーを押してオンにする:
  keydown key=CapsLock CapsLock=false / keyup key=CapsLock CapsLock=true
Caps Lock キーを押してオフにする:
  keydown key=CapsLock CapsLock=true / keyup key=CapsLock CapsLock=true

In this environment, the keydown for the Caps Lock key itself returned the state from before the press. When turning Caps Lock on, keyup returned true, so PasswordField, which re-reads in onKeyUp, could show the warning. When turning it off, keyup still returned true, so the warning stayed until the next key was pressed. The code in this article does not special-case the Caps Lock key's own events. I did not change the code to match the values returned in this environment, because I could not check whether it would work the same way on other OSes and browsers.

Reading only in keydown does not show the warning when entering the field

For comparison, I ran a version that reads only in onKeyDown (KeyDownOnly) under the same conditions.

tsx
<input
  id="k-password"
  type="password"
  value={password}
  onChange={(e) => setPassword(e.target.value)}
  onKeyDown={(e) => setCapsLock(e.getModifierState('CapsLock'))}
/>

Comparing the results with PasswordField gives the following.

Action PasswordField KeyDownOnly
Press Caps Lock to turn it on in the password field Shown Not shown (shown at the next key)
Turn on Caps Lock in the username field, then move to the password field with Tab Shown Not shown
Click the password field while Caps Lock is on Shown Not shown

When moving with Tab, keydown went to the username field before the move, and only keyup reached the password field. When clicking, the event that reached the password field was mousedown. Re-reading in onKeyUp and onMouseDown as well shows the warning before anything is typed. This matters in a password field, because you can notice before the first character is entered, and that character might be an uppercase letter.

Also convey the warning text to screen readers

I gave the warning <p> role="status" and kept the element itself always rendered, changing only its text. status is a live region role for advisory information to the user that is less urgent than alert (MDN: status role). MDN's live regions guide says that a live region's attributes and role must be in place before its content changes. Rendering the <p> only when the warning appears would not meet this condition.

Also, only while the warning is shown, the input's aria-describedby points to the warning's id. aria-describedby is an attribute that links an input to its description by referencing the id of the element that holds the description (MDN: aria-describedby). In testing, aria-describedby="capslock-warning" was present while the warning was shown and removed when it disappeared.

Creating the Caps Lock state in tests

I pressed Caps Lock with Playwright's page.keyboard.press('CapsLock') and then typed "a" in headless Chromium. getModifierState('CapsLock') stayed false, the entered value was lowercase "a", and no warning appeared.

text
keydown key=CapsLock target=password CapsLock=false
keyup key=CapsLock target=password CapsLock=false
keydown key=a target=password CapsLock=false
keyup key=a target=password CapsLock=false
入力された値: a
警告: ""

To check the warning in tests, I sent keyboard events with modifierCapsLock: true to the input. This reproduced the getModifierState value seen when Caps Lock is on.

ts
const pw = page.locator('#password');
await pw.focus();
await pw.dispatchEvent('keydown', { key: 'a', modifierCapsLock: true });
// → The warning shows "Caps Lock is on"
await pw.dispatchEvent('keydown', { key: 'a', modifierCapsLock: false });
// → The warning is empty

This method only verifies that the warning switches according to the value of getModifierState.

​Posted by 86