Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ehabafia's avatar

IMask with Livewire and Alpine

Hi folks,

I am trying to apply IMask js with livewire, which works fine with the following code:

<section class="px-4"
         x-data
         x-init=" IMask( $refs.mobile, { mask: '+{1} (000) 000-0000' }); "
>
<div class="form-group">
    <label class="control-label">Mobile # <x-required /></label>
    <input
            x-ref="mobile"
            wire:model.lazy="mobile"
            type="text"
            class="form-control @error('mobile'){{ 'border border-danger' }} @else {{ 'border border-success' }}@enderror"
            placeholder="(000) 000-0000"
    >
    @error('mobile')<div class="invalid-feedback" style="display: block;" role="alert">{{ $message }}</div>@enderror
</div>
</section>

This works fine, but the thing is I want to unmask it before I submit it to be able to process the unmasked value of the field (unless there is a bitter way).

And is there a solution for any package or just this one.

Thank you,

0 likes
4 replies
whoisthisstud's avatar

I use a controller method to "clean" the phone number before I store it in the database.

<div x-data="{ mask: '(000) 000-0000' }" x-init="IMask($refs.phone, { mask })">
    <x-jet-label for="phone">
        <span>Phone</span>
    </x-jet-label>
    <x-jet-input wire:model="phone" x-ref="phone" name="phone" type="tel"/>
</div>
public function cleanPhoneNumber($phone)
{
    return preg_replace('/[^0-9]/', '', $phone);
}
ehabafia's avatar
Level 37

@whoisthisstud I am trying this approach, but keep getting an error of:

IMask is not defined, although I added this to bootstrap.js

npm install imask
import IMask from 'imask';
window.IMask = IMask;

and I added the field in the livewire blade component:

<div x-data="{ mask: '(000) 000-0000' }" x-init="IMask($refs.phone_number, { mask })"
     class="col-lg-4 col-md-6 col-sm-12 mb-4">
    <x-input name="phone_number"
             wire:model="state.phone_number"
             x-ref="phone_number"
             placeholder="Your Phone Number"
             label="{{ __('Phone Number') }}"
    />

but still no luck, any thoughts of what I am doing wrong?

Please or to participate in this conversation.