Skip to main contentSkip to docs navigation

Chassis

Password strength

View on GitHub

Show the strength of a password as it is typed, with a segmented meter or a progress bar and an optional text message.

@layer components
Requires JavaScript
Depends onForm Input
Context tokens

Introduction

A strength meter scores a password while the user types it and shows the result as one of four levels: weak, fair, good and strong. The plugin computes the score from the length of the password and the kinds of characters in it, and the CSS colors the meter by level.

Key features

The component has two forms and a configurable score:

  • Segmented meter — four segments that fill up to the current level
  • Progress bar — a single bar that grows with the level
  • Text feedback — an optional message for each level
  • Configurable scoring — minimum length, the weight of each criterion, the thresholds of the levels, or a custom scoring function
  • Static display — the same markup shows a fixed level without the plugin

Basic structure

The default meter is a .strength element with four .strength-segment children, placed in the same parent as the password input. Add data-cx-strength to enable the plugin: the segments fill one by one as the strength of the password increases.

HTML
<div>
  <label for="password1" class="form-label">Password</label>
  <input type="password" autocomplete="new-password" class="form-input" id="password1" placeholder="Enter password">
  <div class="strength" data-cx-strength>
    <div class="strength-segment"></div>
    <div class="strength-segment"></div>
    <div class="strength-segment"></div>
    <div class="strength-segment"></div>
  </div>
</div>

Text feedback

Add a .strength-text element next to the meter to display a message for the current level. The plugin writes the message and colors it with the context of the level.

HTML
<div>
  <label for="password2" class="form-label">Password</label>
  <input type="password" autocomplete="new-password" class="form-input" id="password2" placeholder="Enter password">
  <div class="strength" data-cx-strength>
    <div class="strength-segment"></div>
    <div class="strength-segment"></div>
    <div class="strength-segment"></div>
    <div class="strength-segment"></div>
  </div>
  <span class="strength-text" aria-live="polite"></span>
</div>

Progress bar

Use .strength-bar instead of .strength for a single bar that grows with the strength of the password. It needs no child elements.

HTML
<div>
  <label for="password3" class="form-label">Password</label>
  <input type="password" autocomplete="new-password" class="form-input" id="password3" placeholder="Enter password">
  <div class="strength-bar" data-cx-strength></div>
</div>

Static display

A meter shows a fixed level without the plugin when the markup carries the state itself, for content rendered on the server or for a legend of the levels. The plugin leaves a meter alone when its parent holds no password input.

Static segmented

Set data-cx-strength to the level and add .active to as many segments as the level fills.

Weak
Fair
Good
Strong
HTML
<div>
  <div>Weak</div>
  <div class="strength" data-cx-strength="weak">
    <div class="strength-segment active"></div>
    <div class="strength-segment"></div>
    <div class="strength-segment"></div>
    <div class="strength-segment"></div>
  </div>
</div>
<div>
  <div>Fair</div>
  <div class="strength" data-cx-strength="fair">
    <div class="strength-segment active"></div>
    <div class="strength-segment active"></div>
    <div class="strength-segment"></div>
    <div class="strength-segment"></div>
  </div>
</div>
<div>
  <div>Good</div>
  <div class="strength" data-cx-strength="good">
    <div class="strength-segment active"></div>
    <div class="strength-segment active"></div>
    <div class="strength-segment active"></div>
    <div class="strength-segment"></div>
  </div>
</div>
<div>
  <div>Strong</div>
  <div class="strength" data-cx-strength="strong">
    <div class="strength-segment active"></div>
    <div class="strength-segment active"></div>
    <div class="strength-segment active"></div>
    <div class="strength-segment active"></div>
  </div>
</div>
HTML
<!-- Set via server-side logic -->
<div class="strength" data-cx-strength="good">
  <div class="strength-segment active"></div>
  <div class="strength-segment active"></div>
  <div class="strength-segment active"></div>
  <div class="strength-segment"></div>
</div>

Static progress bar

Set data-cx-strength to the level on a .strength-bar; the width and the color of the bar follow from it.

Weak
Fair
Good
Strong
HTML
<div>
  <div>Weak</div>
  <div class="strength-bar" data-cx-strength="weak"></div>
</div>
<div>
  <div>Fair</div>
  <div class="strength-bar" data-cx-strength="fair"></div>
</div>
<div>
  <div>Good</div>
  <div class="strength-bar" data-cx-strength="good"></div>
</div>
<div>
  <div>Strong</div>
  <div class="strength-bar" data-cx-strength="strong"></div>
</div>

Strength criteria

The default scoring gives a password one point for each criterion it meets:

CriteriaPoints
Meets minimum length (8 characters)+1
4+ characters over minimum+1
Contains lowercase letters+1
Contains uppercase letters+1
Contains numbers+1
Contains special characters+1
Multiple special characters+1
16+ characters+1

The score maps to a level through the thresholds option. An empty password has no level.

LevelPoints
Weak1-2
Fair3-4
Good5-6
Strong7-8

Accessibility

The meter conveys the strength through color and size only, and the plugin sets no ARIA attribute. Three practices make the feedback available to everyone:

  • State the password requirements in text next to the input, and associate that text with the input through aria-describedby.
  • Add the .strength-text element, so the level is also available as text.
  • Add aria-live="polite" to the .strength-text element so screen readers announce the level when it changes.

JavaScript API

The Strength plugin scores the password of an input, updates the meter and the text, and fires an event when the level changes. Chassis JS ships as an ES module — import the Strength class:

JavaScript
import { Strength } from '@chassis-ui/css'

Triggers

An element with data-cx-strength is initialized when the page loads. The plugin uses the first input[type="password"] in the parent of that element, unless data-cx-input names another one.

AttributeDescription
data-cx-strengthInitializes the strength indicator on the element (.strength or .strength-bar).
data-cx-inputCSS selector for the password field when it is not in the same parent as the meter.
data-cx-min-lengthMinimum length used when computing the strength score.
HTML
<div>
  <input type="password" autocomplete="new-password" class="form-input">
  <div class="strength" data-cx-strength>
    <div class="strength-segment"></div>
    <div class="strength-segment"></div>
    <div class="strength-segment"></div>
    <div class="strength-segment"></div>
  </div>
</div>

Initialization

Create an instance with the Strength class to pass the options as an object, such as the messages or a scoring function:

JavaScript
const element = document.querySelector('.strength')
const strength = new Strength(element, {
  input: '#my-password-input',
  minLength: 10,
  messages: {
    weak: 'Too weak',
    fair: 'Could be better',
    good: 'Good password',
    strong: 'Excellent!'
  }
})

Methods

The plugin exposes instance methods to read the level and to score the password again:

MethodDescription
getStrength()Returns the current strength level ('weak', 'fair', 'good', 'strong', or null).
evaluate()Scores the current value of the input again, for example after a script has changed it.
dispose()Destroys the component instance.
getInstance(element)Static — returns the instance bound to an element, or null.
getOrCreateInstance(element)Static — returns the instance bound to an element, or creates one.
JavaScript
const element = document.querySelector('.strength')
const strength = Strength.getOrCreateInstance(element)

// Get current strength
console.log(strength.getStrength()) // 'fair'

Options

Options are set via data-cx-* attributes or passed to the constructor as an object. Attribute names use the kebab-case form of the option name — data-cx-custom-class, not data-cx-customClass. Attribute values are parsed to their native types:"true" → true, "0" → 0, and valid JSON strings to objects.

Use data-cx-config to pass multiple options as a JSON string:data-cx-config='{"delay":200}'. Individual data-cx-* attributes take precedence over data-cx-config. Individual attributes accept JSON values too, such as data-cx-delay='{"show":100,"hide":200}'.

When initializing components, Chassis merges configurations from multiple sources in this priority order: default settings, data-cx-config values, individual data-cx-*attributes, and finally any JavaScript object options. Values defined later in this sequence override earlier ones.

NameTypeDefaultDescription
inputstring | elementnullSelector or element for the password input. If not provided, the plugin uses the first input[type="password"] in the parent of the meter.
minLengthnumber8Minimum password length for first strength point.
messagesobject{weak, fair, good, strong}Custom messages for each strength level.
weightsobject1 for each criterionPoint values for each scoring criterion. Set one to 0 to disable the criterion.
thresholdsarray[2, 4, 6]Score boundaries for strength levels: [weak, fair, good]. Scores above the last value are "strong".
scorerfunctionnullCustom scoring function (password) => number. Overrides built-in scoring when provided.

The weights object has one key for each criterion of the default scoring:

JavaScript
{
  minLength: 1,        // Meets minimum length
  extraLength: 1,      // 4+ characters over minimum
  lowercase: 1,        // Contains lowercase letters
  uppercase: 1,        // Contains uppercase letters
  numbers: 1,          // Contains numbers
  special: 1,          // Contains special characters
  multipleSpecial: 1,  // Multiple special characters
  longPassword: 1      // 16+ characters
}

Changed weights change the highest possible score, so adjust thresholds with them:

JavaScript
// Disable uppercase requirement, make special chars worth more
new Strength(element, {
  weights: {
    uppercase: 0,   // Don't require uppercase
    special: 2      // Special chars worth 2 points
  },
  thresholds: [3, 5, 7]  // Adjust thresholds for new max score
})

A scorer function replaces the default scoring altogether; the thresholds still map its result to a level:

JavaScript
// Fully custom scoring logic
new Strength(element, {
  scorer: (password) => {
    let score = 0
    if (password.length >= 12) score += 4
    if (/[!@#$%]/.test(password)) score += 4
    return score
  },
  thresholds: [2, 4, 6]
})

Events

The event fires on the element with data-cx-strength, and only when the level changes, not on every keystroke.

EventDescription
strengthChange.cx.strengthFired when the strength level changes. Includes the strength and score properties; the password itself is not part of the event.
JavaScript
const element = document.querySelector('.strength')

element.addEventListener('strengthChange.cx.strength', event => {
  console.log('Strength:', event.strength) // 'weak', 'fair', 'good', 'strong' or null
  console.log('Score:', event.score) // 0-8
})

CSS

The Password strength component can be customized at both runtime (via custom properties) and compile time (via Sass variables).

Custom properties

The Password strength component exposes CSS custom properties to control its appearance at runtime.

// stylelint-disable-next-line scss/dollar-variable-default
$strength-tokens: defaults(
  (
    --strength-height: #{$form-password-strength-height},
    --strength-gap: #{$form-password-strength-gap},
    --strength-margin-top: #{$form-password-strength-margin-top},
    --strength-border-radius: #{$form-password-strength-border-radius},
    --strength-font-size: #{$form-password-strength-font-size},
    --strength-bg: #{$form-password-strength-bg},
    --strength-color: #{$form-password-strength-color},
    --strength-weak-color: #{$form-password-strength-weak-color},
    --strength-fair-color: #{$form-password-strength-fair-color},
    --strength-good-color: #{$form-password-strength-good-color},
    --strength-strong-color: #{$form-password-strength-strong-color},
  ),
  $strength-tokens
);

Sass variables

The Password strength component uses Sass variables in scss/config/_defaults.scss to define its defaults; they are also exposed as CSS custom properties using the --cx- prefix for runtime override — $variable-name becomes --cx-variable-name. See the component anatomy page.

$form-password-strength-height:             .375rem;
$form-password-strength-gap:                .25rem;
$form-password-strength-margin-top:         .5rem;
$form-password-strength-border-radius:      var(--border-radius-full);
$form-password-strength-font-size:          var(--font-size-ui-sm);
$form-password-strength-bg:                 var(--bg-evident);
$form-password-strength-color:              var(--bg-evident);
$form-password-strength-weak-color:         var(--danger);
$form-password-strength-fair-color:         var(--warning);
$form-password-strength-good-color:         var(--info);
$form-password-strength-strong-color:       var(--success);

Strength levels

The $strength-levels Sass list names the levels that the CSS styles. The order of the list matters: the position of a level sets the width of the progress bar, in steps of 25%.

$strength-levels: weak, fair, good, strong;