Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions packages/alpinejs/src/utils/bind.js
Original file line number Diff line number Diff line change
Expand Up @@ -135,11 +135,23 @@ function checkedAttrLooseCompare(valueA, valueB) {
}

export function safeParseBoolean(rawValue) {
if ([1, '1', 'true', 'on', 'yes', true].includes(rawValue)) {
if ([1, true].includes(rawValue)) {
return true
}

if ([0, '0', 'false', 'off', 'no', false].includes(rawValue)) {
if ([0, false].includes(rawValue)) {
return false
}

let normalizedString = typeof rawValue === 'string'
? rawValue.trim().toLowerCase()
: rawValue

if (['1', 'true', 'on', 'yes'].includes(normalizedString)) {
return true
}

if (['0', 'false', 'off', 'no'].includes(normalizedString)) {
return false
}

Expand Down
2 changes: 1 addition & 1 deletion packages/docs/src/en/directives/model.md
Original file line number Diff line number Diff line change
Expand Up @@ -385,7 +385,7 @@ By default, any data stored in a property via `x-model` is stored as a string. T
<a name="boolean"></a>
### `.boolean`

By default, any data stored in a property via `x-model` is stored as a string. To force Alpine to store the value as a JavaScript boolean, add the `.boolean` modifier. Both integers (1/0) and strings (true/false) are valid boolean values.
By default, any data stored in a property via `x-model` is stored as a string. To force Alpine to store the value as a JavaScript boolean, add the `.boolean` modifier. Both integers (1/0) and strings (true/false) are valid boolean values. Matching is case-insensitive and ignores surrounding whitespace.

```alpine
<select x-model.boolean="isActive">
Expand Down
28 changes: 28 additions & 0 deletions tests/vitest/bind.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// @vitest-environment jsdom

import { beforeAll, describe, expect, it } from 'vitest'
import Alpine from '../../packages/alpinejs/src/index.js'

let safeParseBoolean

beforeAll(async () => {
Alpine.start()
safeParseBoolean = (await import('../../packages/alpinejs/src/utils/bind.js')).safeParseBoolean
})

describe('safeParseBoolean', () => {
it('handles mixed case and surrounding whitespace for known values', () => {
expect(safeParseBoolean(' TRUE ')).toBe(true)
expect(safeParseBoolean(' yes ')).toBe(true)
expect(safeParseBoolean(' 1 ')).toBe(true)

expect(safeParseBoolean(' FALSE ')).toBe(false)
expect(safeParseBoolean(' off ')).toBe(false)
expect(safeParseBoolean(' 0 ')).toBe(false)
})

it('keeps legacy fallback behavior for unknown values', () => {
expect(safeParseBoolean('unknown')).toBe(true)
expect(safeParseBoolean('')).toBe(null)
})
})