Enter a password, show or hide it, and use it in a native form.

A Password Input is a native password field with a button that shows and hides what's typed. It keeps the caret in place, offers the right password to password managers, and hides the password again when its form submits.

<script lang="ts">
  import { EyeIcon, EyeOffIcon } from "@lucide/svelte"
  import { Field, FieldDescription, FieldLabel } from "@ui-sdk/svelte/field"
  import {
    PasswordInput,
    PasswordInputControl,
    PasswordInputToggle,
  } from "@ui-sdk/svelte/password-input"
</script>

<Field name="password">
  <FieldLabel>Password</FieldLabel>
  <PasswordInput>
    <PasswordInputControl />
    <PasswordInputToggle aria-label="Show password">
      {#snippet children(state)}
        {#if state.visible}
          <EyeOffIcon aria-hidden="true" />
        {:else}
          <EyeIcon aria-hidden="true" />
        {/if}
      {/snippet}
    </PasswordInputToggle>
  </PasswordInput>
  <FieldDescription>Use at least 8 characters.</FieldDescription>
</Field>
Type a password, then choose Show password to reveal or hide it. Clicking the toggle keeps the caret in the field. With a keyboard, Tab to the toggle and press Space or Enter.

Installation

npm install @ui-sdk/svelte @ui-sdk/core

Composition

Use the following composition to build a PasswordInput:

PasswordInput
โ”œโ”€โ”€ PasswordInputControl
โ””โ”€โ”€ PasswordInputToggle

PasswordInput holds the value and visibility state. PasswordInputControl renders the native input; PasswordInputToggle renders the button that shows and hides it. The toggle switches the input between password and text, and is a type="button", so pressing Enter in the input still submits the form.

Put form options such as name, form, required, disabled, and readOnly on PasswordInput. Put other native input attributes, such as placeholder or id, on PasswordInputControl.

Usage

Import the parts and put them together:

<script lang="ts">
  import {
    PasswordInput,
    PasswordInputControl,
    PasswordInputToggle,
  } from "@ui-sdk/svelte/password-input"
</script>

<PasswordInput name="password">
  <PasswordInputControl aria-label="Password" />
  <PasswordInputToggle aria-label="Show password">Show</PasswordInputToggle>
</PasswordInput>

New Password

Use autoComplete="new-password" on the root when creating or changing a password. It tells the browser and password manager which kind of password to offer. The default is current-password for signing in.

The example derives a checklist from the current value. Those rules belong to the example; the component does not impose a password policy.

<script lang="ts">
  import { CheckIcon, EyeIcon, EyeOffIcon, XIcon } from "@lucide/svelte"
  import { Field, FieldLabel } from "@ui-sdk/svelte/field"
  import {
    PasswordInput,
    PasswordInputControl,
    PasswordInputToggle,
  } from "@ui-sdk/svelte/password-input"

  const rules = [
    {
      label: "At least 8 characters",
      test: (password: string) => password.length >= 8,
    },
    { label: "A number", test: (password: string) => /\d/.test(password) },
    {
      label: "An uppercase and a lowercase letter",
      test: (password: string) =>
        /[a-z]/.test(password) && /[A-Z]/.test(password),
    },
  ]

  let password = $state("")
</script>

<Field name="new-password">
  <FieldLabel>Create a password</FieldLabel>
  <PasswordInput
    value={password}
    autoComplete="new-password"
    onValueChange={(value: string) => (password = value)}
  >
    <PasswordInputControl />
    <PasswordInputToggle aria-label="Show password">
      {#snippet children(state)}
        {#if state.visible}
          <EyeOffIcon aria-hidden="true" />
        {:else}
          <EyeIcon aria-hidden="true" />
        {/if}
      {/snippet}
    </PasswordInputToggle>
  </PasswordInput>
  <ul data-slot="stack" aria-label="Password requirements">
    {#each rules as rule (rule.label)}
      {#if rule.test(password)}
        <li data-slot="row">
          <CheckIcon aria-hidden="true" />
          <span data-slot="visually-hidden">Done:</span>
          {rule.label}
        </li>
      {:else}
        <li data-slot="row">
          <XIcon aria-hidden="true" />
          <span data-slot="visually-hidden">To do:</span>
          {rule.label}
        </li>
      {/if}
    {/each}
  </ul>
</Field>
Type a password and watch the checklist update. Try adding digits and both uppercase and lowercase letters, then toggle its visibility.

Shown at First

Set defaultVisible to start with the text visible, and defaultValue for its initial value. This can be useful for a Wi-Fi password someone needs to read or copy.

<script lang="ts">
  import { EyeIcon, EyeOffIcon } from "@lucide/svelte"
  import { Field, FieldDescription, FieldLabel } from "@ui-sdk/svelte/field"
  import {
    PasswordInput,
    PasswordInputControl,
    PasswordInputToggle,
  } from "@ui-sdk/svelte/password-input"
</script>

<Field name="wifi-password">
  <FieldLabel>Wi-Fi password</FieldLabel>
  <PasswordInput
    defaultVisible
    defaultValue="maple-orbit-42"
    autoComplete="new-password"
  >
    <PasswordInputControl />
    <PasswordInputToggle aria-label="Show password">
      {#snippet children(state)}
        {#if state.visible}
          <EyeOffIcon aria-hidden="true" />
        {:else}
          <EyeIcon aria-hidden="true" />
        {/if}
      {/snippet}
    </PasswordInputToggle>
  </PasswordInput>
  <FieldDescription
    >Guests read it from here, so it starts shown.</FieldDescription
  >
</Field>
Read the Wi-Fi password, then choose Show password to hide it. Choose it again to reveal the value.

Caps Lock

Use data-capslock or the part's capsLock state for a warning. It updates from key events while the input is focused. The example reserves space for the icon and warning.

<script lang="ts">
  import { EyeIcon, EyeOffIcon, LockIcon } from "@lucide/svelte"
  import { Field, FieldLabel } from "@ui-sdk/svelte/field"
  import {
    PasswordInput,
    PasswordInputControl,
    PasswordInputToggle,
  } from "@ui-sdk/svelte/password-input"
</script>

<Field name="password">
  <FieldLabel>Password</FieldLabel>
  <PasswordInput>
    {#snippet children(state)}
      <PasswordInputControl />
      <span
        >{#if state.capsLock}<LockIcon aria-hidden="true" />{/if}</span
      >
      <PasswordInputToggle aria-label="Show password">
        {#snippet children(toggle)}
          {#if toggle.visible}
            <EyeOffIcon aria-hidden="true" />
          {:else}
            <EyeIcon aria-hidden="true" />
          {/if}
        {/snippet}
      </PasswordInputToggle>
    {/snippet}
  </PasswordInput>
  <p data-slot="caps-lock">Caps Lock is on.</p>
</Field>
Focus Password and press Caps Lock. The warning appears while Caps Lock is on. Turn it off or leave the field to hide the warning.

Disabled

Set disabled on the root, its Field, or an enclosing fieldset to disable both the input and the toggle. The value is omitted from form submission.

<script lang="ts">
  import { EyeIcon, EyeOffIcon } from "@lucide/svelte"
  import { Field, FieldDescription, FieldLabel } from "@ui-sdk/svelte/field"
  import {
    PasswordInput,
    PasswordInputControl,
    PasswordInputToggle,
  } from "@ui-sdk/svelte/password-input"
</script>

<Field disabled name="password">
  <FieldLabel>Password</FieldLabel>
  <PasswordInput defaultValue="hunter22">
    <PasswordInputControl />
    <PasswordInputToggle aria-label="Show password">
      {#snippet children(state)}
        {#if state.visible}
          <EyeOffIcon aria-hidden="true" />
        {:else}
          <EyeIcon aria-hidden="true" />
        {/if}
      {/snippet}
    </PasswordInputToggle>
  </PasswordInput>
  <FieldDescription>Your administrator manages this password.</FieldDescription>
</Field>
Try to edit Password or press its toggle. Both controls are disabled and are skipped by Tab.

Read-Only

Set readOnly when the value can be read but not edited. The input stays focusable, the toggle still works, and the value still participates in form submission.

<script lang="ts">
  import { EyeIcon, EyeOffIcon } from "@lucide/svelte"
  import { Field, FieldDescription, FieldLabel } from "@ui-sdk/svelte/field"
  import {
    PasswordInput,
    PasswordInputControl,
    PasswordInputToggle,
  } from "@ui-sdk/svelte/password-input"
</script>

<Field name="recovery-key">
  <FieldLabel>Recovery key</FieldLabel>
  <PasswordInput readOnly defaultValue="7Hq2-vX9p-Lm4c" autoComplete="off">
    <PasswordInputControl />
    <PasswordInputToggle aria-label="Show recovery key">
      {#snippet children(state)}
        {#if state.visible}
          <EyeOffIcon aria-hidden="true" />
        {:else}
          <EyeIcon aria-hidden="true" />
        {/if}
      {/snippet}
    </PasswordInputToggle>
  </PasswordInput>
  <FieldDescription
    >Keep it somewhere safe. You can show it, but not change it.</FieldDescription
  >
</Field>
Choose Show recovery key to read it. Try to type in the input; its value stays unchanged.

Controlled Visibility

Bind visible with bind:visible to control visibility, and use onVisibleChange for the details. The reason distinguishes a toggle press, form submission, reset, page hide, or a controller action.

Console
<script lang="ts">
  import { EyeIcon, EyeOffIcon } from "@lucide/svelte"
  import { Field, FieldLabel } from "@ui-sdk/svelte/field"
  import {
    PasswordInput,
    PasswordInputControl,
    PasswordInputToggle,
  } from "@ui-sdk/svelte/password-input"
  import { useLog } from "./log"

  const log = useLog()
  let visible = $state(false)
</script>

<Field name="password">
  <FieldLabel>Password</FieldLabel>
  <PasswordInput
    bind:visible
    onVisibleChange={(next: boolean, details: { reason: string }) =>
      log(`${next ? "Shown" : "Hidden"} (${details.reason})`)}
  >
    <PasswordInputControl />
    <PasswordInputToggle aria-label="Show password">
      {#snippet children(state)}
        {#if state.visible}
          <EyeOffIcon aria-hidden="true" />
        {:else}
          <EyeIcon aria-hidden="true" />
        {/if}
      {/snippet}
    </PasswordInputToggle>
  </PasswordInput>
</Field>
Toggle Show password. The console logs each change and its reason.

Call details.cancel() in the change callback to reject a visibility change. During form submission, the native input is temporarily a password field even if the callback rejects hiding it.

Controller

Create a createPasswordInputController() and pass it as controller for actions outside the input. Read or change the value, toggle visibility, or focus the input. Writes use the imperative reason.

Console
<script lang="ts">
  import { EyeIcon, EyeOffIcon } from "@lucide/svelte"
  import { Field, FieldLabel } from "@ui-sdk/svelte/field"
  import {
    createPasswordInputController,
    PasswordInput,
    PasswordInputControl,
    PasswordInputToggle,
  } from "@ui-sdk/svelte/password-input"
  import { useLog } from "./log"

  const log = useLog()
  const password = createPasswordInputController()
</script>

<div data-slot="stack">
  <div data-slot="controls">
    <button
      type="button"
      onclick={() => {
        password.setValue("plum-kettle-orbit-42")
        password.setVisible(true)
      }}
    >
      Suggest
    </button>
    <button type="button" onclick={() => password.toggleVisible()}
      >Toggle</button
    >
    <button type="button" onclick={() => password.clear()}>Clear</button>
    <button
      type="button"
      onclick={() =>
        log(
          `${password.getValue().length} characters, ${password.isVisible() ? "shown" : "hidden"}`
        )}
    >
      Read
    </button>
    <button type="button" onclick={() => password.focus()}>Focus</button>
  </div>
  <Field name="new-password">
    <FieldLabel>New password</FieldLabel>
    <PasswordInput controller={password} autoComplete="new-password">
      <PasswordInputControl />
      <PasswordInputToggle aria-label="Show password">
        {#snippet children(state)}
          {#if state.visible}
            <EyeOffIcon aria-hidden="true" />
          {:else}
            <EyeIcon aria-hidden="true" />
          {/if}
        {/snippet}
      </PasswordInputToggle>
    </PasswordInput>
  </Field>
</div>
Choose Suggest to fill and reveal a sample value. Try Toggle, Read, Clear, and Focus to call each action from outside the field.

Controllers covers how to create and share a controller.

Forms

The native input participates in FormData, validation, and reset. Use form to associate it with a form elsewhere in the page, as this example does.

Console
<script lang="ts">
  import { EyeIcon, EyeOffIcon } from "@lucide/svelte"
  import { Field, FieldLabel } from "@ui-sdk/svelte/field"
  import { Input } from "@ui-sdk/svelte/input"
  import {
    PasswordInput,
    PasswordInputControl,
    PasswordInputToggle,
  } from "@ui-sdk/svelte/password-input"
  import { useLog } from "./log"

  const log = useLog()
</script>

<div data-slot="stack">
  <form
    data-slot="stack"
    id="sign-in"
    onsubmit={(event) => {
      event.preventDefault()
      const data = new FormData(event.currentTarget)
      const length = String(data.get("password")).length
      log(
        `Signed in as ${data.get("email")}, with a password of ${length} characters`
      )
    }}
  >
    <Field name="email">
      <FieldLabel>Email</FieldLabel>
      <Input type="email" required autocomplete="username" />
    </Field>
  </form>
  <Field>
    <FieldLabel>Password</FieldLabel>
    <PasswordInput name="password" form="sign-in" required>
      <PasswordInputControl />
      <PasswordInputToggle aria-label="Show password">
        {#snippet children(state)}
          {#if state.visible}
            <EyeOffIcon aria-hidden="true" />
          {:else}
            <EyeIcon aria-hidden="true" />
          {/if}
        {/snippet}
      </PasswordInputToggle>
    </PasswordInput>
  </Field>
  <div data-slot="row">
    <button type="submit" form="sign-in" data-variant="solid">Sign In</button>
    <button type="reset" form="sign-in">Reset</button>
  </div>
</div>
Enter an email and password, reveal the password, then press Enter in the field. Submission hides it again, and the console logs its length. Reset clears the form. Empty required fields block submission.

Submission, reset, and page hiding request that the password be hidden again. A reset also restores its default value. Spellcheck, autocorrection, and automatic capitalization stay disabled when the password is visible.

Controlled Value

Bind the password with bind:value, or pass value and handle onValueChange. The New Password example derives its checklist this way. State and Events covers the shared state conventions.

<script lang="ts">
  let password = $state("")
</script>

<PasswordInput bind:value={password}>
  <PasswordInputControl aria-label="Password" />
  <PasswordInputToggle aria-label="Show password">Show</PasswordInputToggle>
</PasswordInput>

Custom Rendering

Every part takes a render snippet, which receives the props to spread and the part's state, and the children snippet receives the state too: whether the password is visible, whether Caps Lock is on (capsLock), and whether the field is filled. See Parts and Composition for the rendering conventions.

<PasswordInputToggle aria-label="Show password">
  {#snippet render({ props, state })}
    <button {...props}>
      {#if state.visible}
        <EyeOffIcon aria-hidden="true" />
      {:else}
        <EyeIcon aria-hidden="true" />
      {/if}
    </button>
  {/snippet}
</PasswordInputToggle>

Styling

Style the root as the field's box, with the native input and the toggle inside it. data-visible marks every part while the password is shown, and the toggle also sets aria-pressed. Use data-capslock for a Caps Lock warning, and data-filled, data-disabled and data-readonly for the field's other states. Inside Field, the native input also receives validation attributes such as data-invalid. Use logical spacing so the field and toggle follow the surrounding direction.

Each part has a data-slot, such as password-input-toggle, and its state attributes are listed under Data Attributes.

Data Attributes

PasswordInput

[data-slot="password-input"]

AttributeWhat it means
data-visiblePresent while the password is shown, so the field is a text field.
data-filledPresent while the field holds any text.
data-disabledPresent when disabled, by its own prop, a Field or a <fieldset>.
data-readonlyPresent when the field is read-only.
data-requiredPresent when a password is required.
data-capslockPresent while Caps Lock is on and the field has focus.

PasswordInputControl

[data-slot="password-input-control"]

AttributeWhat it means
data-visiblePresent while the password is shown, so the field is a text field.
data-filledPresent while the field holds any text.
data-disabledPresent when disabled, by its own prop, a Field or a <fieldset>.
data-readonlyPresent when the field is read-only.
data-requiredPresent when a password is required.
data-capslockPresent while Caps Lock is on and the field has focus.

PasswordInputToggle

[data-slot="password-input-toggle"]

AttributeWhat it means
data-visiblePresent while the password is shown, so the field is a text field.
data-filledPresent while the field holds any text.
data-disabledPresent when disabled, by its own prop, a Field or a <fieldset>.
data-readonlyPresent when the field is read-only.
data-requiredPresent when a password is required.
data-capslockPresent while Caps Lock is on and the field has focus.

API Reference

Props and callbacks are the same as below, as Svelte props. value and visible can be bound with bind:value and bind:visible.

PasswordInput

value?string
The value, for a controlled field.
defaultValue?string
The value it starts with. A form reset returns here.
onValueChange?((value: string, details: ChangeDetails<InputValueChangeReason>) => void)
Called when the user changes the value: typing ("input-change"), a Clear part ("clear-press"), a form reset ("reset") or a controller ("imperative"). details.cancel() keeps the value as it was.
visible?boolean
Whether the password is shown. Pass it to control it.
defaultVisible?boolean
Whether the password is shown at first, when uncontrolled.
onVisibleChange?((visible: boolean, details: ChangeDetails<PasswordInputVisibleChangeReason>) => void)
Runs when the password wants to be shown or hidden: the toggle ("toggle-press"), submitting or resetting its form ("form-submit", "reset"), the page being hidden ("page-hide") or a controller ("imperative"). details.cancel() keeps it as it was; the field is a password field while the browser reads a submitted form either way.
autoComplete?"current-password" | "new-password" | "off" | (string & {})
What the browser and password managers fill in: "current-password" for signing in, "new-password" for signing up or changing it.
name?string
The name the password submits under. Inside a Field, the Field's name.
form?string
The id of the form the field belongs to, when it isn't inside it.
required?boolean
Whether a password is required to submit the form.
disabled?boolean
Disables the field and the toggle. Inside a Field or a disabled <fieldset>, they follow it.
readOnly?boolean
Makes the field read-only. The toggle still shows and hides it.
controller?object
Reads, writes, shows and hides it from anywhere. Create one with createPasswordInputController().
debug?boolean
Logs every state change with its reason to the console, in development builds.

State

What render functions, state-based class names and slots receive. Every part gets the same state.

visibleboolean
Whether the password is shown.
capsLockboolean
Whether Caps Lock is on while the field has focus.
filledboolean
Whether the field holds any text.
disabledboolean
Whether the field is disabled, by itself, its Field or a <fieldset>.
readOnlyboolean
Whether the field is read-only.
requiredboolean
Whether a form won't submit while the field is empty.

Reasons

details.reason says why the value changed. Autofill and a password manager's fill are input-change.

input-changeEvent
Typing, pasting or dropping changed a text field's value; in a combobox it can also open or close it, or Enter keeps the typed text as the value.
clear-pressMouseEvent | KeyboardEvent
A Clear part was pressed, like on an input, a select or a combobox.
resetnone
A form reset.
imperativenone
A controller or api call, or a property set on a web component.

And why the password was shown or hidden:

toggle-pressMouseEvent | KeyboardEvent
A toggle was pressed: a password input's, which shows or hides the password, or a carousel's, which starts or stops rotation.
form-submitSubmitEvent
The form was submitted, which hides a shown password so the browser offers to save it.
resetnone
A form reset.
page-hidePageTransitionEvent
The page was hidden, like when navigating away, which hides a shown password before the browser keeps the page.
imperativenone
A controller or api call, or a property set on a web component.

Controller

Create one with createPasswordInputController() and pass it as controller.

Every write method takes an optional { reason, event }, and runs the change callback like typing or a press. setVisible() and toggleVisible() return false when the change is canceled.

getValue()() => string
The current value.
setValue(value, options?)(value: string, options?: ChangeOptions<InputValueChangeReason> | undefined) => boolean
Sets the value as if the user typed it, so input fires. Returns false when the change was canceled or nothing changed.
clear(options?)(options?: ChangeOptions<InputValueChangeReason> | undefined) => boolean
Empties the field, as if the user deleted the text, so input fires. Returns false when the change was canceled or nothing changed.
isVisible()() => boolean
Whether the password is shown.
setVisible(visible, options?)(visible: boolean, options?: ChangeOptions<PasswordInputVisibleChangeReason> | undefined) => boolean
Shows or hides the password. Returns false when canceled.
toggleVisible(options?)(options?: ChangeOptions<PasswordInputVisibleChangeReason> | undefined) => boolean
Shows the password if it's hidden, and hides it if it's shown. Returns false when canceled.
focus()() => void
Moves focus to the field.

Events

Callbacks get the new value first, then the details. A bound prop only updates when the callback didn't cancel the change.

PropOnReceives
bind:valuePasswordInputThe password
bind:visiblePasswordInputWhether the password is shown
onValueChangePasswordInput(value, details): the new password and the reason
onVisibleChangePasswordInput(visible, details): whether the password wants to show, and the reason

Accessibility

There's no WAI-ARIA pattern for a password field. The input stays a native password field named by its Field label or an aria-label, and the toggle follows the WAI-ARIA button pattern as a toggle button. Name the toggle by what it does, such as โ€œShow passwordโ€, and keep that name the same: its aria-pressed state tells screen readers whether the password is shown, and aria-controls points to the input.

Keyboard

Tab moves from the input to the toggle, and Space or Enter on the toggle shows or hides the password. Enter in the input submits its form; it never presses the toggle.

Focus

A pointer press on the toggle keeps focus in the input, with the caret and selection where they were. A press from elsewhere brings focus back to the input. A keyboard press keeps focus on the toggle.

Tested Behavior

Every line below is an automated test.

  • The field is a password field named by its label and described by its description.
  • The toggle is a button that says what it does, and isn't pressed.
  • Pressing the toggle shows the password, and pressing it again hides it.
  • Space on the focused toggle shows the password and keeps focus on the toggle.
  • Enter on the focused toggle shows the password and keeps focus on the toggle.
  • The toggle keeps its name when the password shows.
  • Enter in the field submits the form, and never presses the toggle.
  • The password submits under its name.
  • The password can start shown.
  • A change can be canceled.
  • A disabled password input disables the field and the toggle.
  • A read-only field can still be shown.
  • The controller shows and hides the password.
  • A controlled password input follows its owner. React and Vue only.
  • A click with no pointer behind it, like a screen reader's, shows the password.

Runs in React, Vue and web components.

Beyond the pattern:

  • Showing the password keeps focus in the field, with the caret where it was.
  • Showing and hiding the password keeps the selection.
  • A click on the toggle while typing never blurs the field.
  • A click on the toggle from elsewhere brings focus back to the field.
  • Submitting hides a shown password before the page's own submit handler runs.
  • Submitting hides the password even when the change is canceled, while the browser reads the form.
  • Resetting the form hides the password.
  • Hiding the page hides the password, so the browser never keeps it as text.
  • A shown password is never spellchecked, autocorrected or capitalized.
  • The field asks password managers for the current password, or a new one.
  • Caps Lock marks the input while the field has focus.
  • A click into the field with Caps Lock on shows the warning before any key.
  • A web field keeps an autocomplete changed after it connects. Web components only.
  • The toggle has its own id and controls the field.
  • A disabled fieldset disables the toggle too.

Runs in React, Vue and web components.

Screen readers hear the same thing in each tested framework, recorded by a virtual screen reader:

  • Announcements while showing and hiding a password with a keyboard.

Runs in React, Vue and web components.

Also tested:

  • No axe violations at rest.
  • No axe violations with the password shown.
  • No axe violations while disabled.
  • No axe violations while read-only.
  • The field is named by its label, and the toggle by its aria-label.
  • Accessibility tree.

Runs in React, Vue and web components.