Skip to content
Open
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
8 changes: 8 additions & 0 deletions packages/mask/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,14 @@ export default function (Alpine) {

let updater = el._x_forceModelUpdate
el._x_forceModelUpdate = (value) => {
// If the model value was cleared (e.g. the parent object was
// removed), just clear the input — don't format and write back
// as that would resurrect the model path with an empty value.
if (value === undefined) {
lastInputValue = ''
return updater(value)
}

value = String(value)
let template = templateFn(value)
if (template && template !== 'false') {
Expand Down
32 changes: 31 additions & 1 deletion tests/cypress/integration/plugins/mask.spec.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { haveData, haveValue, html, test } from '../../utils'
import { haveData, haveText, haveValue, html, test } from '../../utils'

test('x-mask',
[html`<input x-data x-mask="(999) 999-9999">`],
Expand Down Expand Up @@ -293,3 +293,33 @@ test('x-mask masks programmatic x-model updates',
get('div').should(haveData('value', '23,420'))
}
)

test('x-mask with x-model initializes missing object key',
[html`
<div x-data="{ form: {} }">
<input x-model="form.amount" x-mask:dynamic="$money($input)" id="1">
<span id="output" x-text="'amount' in form ? 'EXISTS:' + form.amount : 'GONE'"></span>
</div>
`],
({ get }) => {
get('#output').should(haveText('EXISTS:'))
get('#1').type('1234').should(haveValue('1,234'))
get('#output').should(haveText('EXISTS:1,234'))
}
)

test('x-mask does not resurrect x-model value when model is cleared',
[html`
<div x-data="{ form: { amount: '5000' } }">
<input x-model="form.amount" x-mask:dynamic="$money($input)">
<span id="output" x-text="'amount' in form ? 'EXISTS' : 'GONE'"></span>
<button @click="form = {}">clear</button>
</div>
`],
({ get }) => {
get('input').should(haveValue('5,000'))
get('#output').should(haveText('EXISTS'))
get('button').click()
get('#output').should(haveText('GONE'))
}
)
Loading