Arms crossed picture of James Auble
3d printed head wearing covid mask

Improve Your Inputs With AlpineJS's New x-mask Plugin

Published

Caleb and the people behind AlpineJS and their wonderful plugins have struck again! This time with a new plugin that formats input values as you type and it goes by the directive x-mask.

From the x-mask page within AlpineJS's official docs:

Alpine's Mask plugin allows you to automatically format a text input field as a user types.
This is useful for many different types of inputs: phone numbers, credit cards, dollar amounts, account numbers, dates, etc.

As I normally do when the micro framework drops something new--I decided to give it a whirl with a simple CodePen demo.

After replicating a few of the examples from the official docs, I decided to push myself a little and do something a little more complex.

International Number Switcher Dynamic Mask 

I'm sure you've all encountered one on the web: an input control group with a dropdown on the left for the international calling code, and a number (or pseudo number) field on the right for the rest of the number.

The Alpine Component 

<script>
    function intCodesComponent() {
      return {
        intCodes: [
            {
              name: "Korea, Republic of South Korea",
              dial_code: "+82",
              code: "KR",
              format: '99 9999 9999'
            },
            {
              name: "United States",
              dial_code: "+1",
              code: "US",
              format: '(999) 999-9999'
            }
        ],
        selectedDialCode: '+1',
        selectedFormat: '(999) 999-9999',
        onSelectChangeHandler(e) {
          const country = intCodes.find((element) => {
            return element.dial_code == this.selectedDialCode
          })
          
          this.selectedFormat = country.format
        },
      }
    }
  </script>

Not much logic to it really. Alpine's reactivity takes care of most of it.

The steps I took were:

  1. Store an array of country code data and their respective phone number format
  2. Create a handler function for the <select> element that updates our selectedFormat reactive property
  3. Use our new x-mask:dynamic directive on the text input and pass it our selectedFormat

The Demo 

Leave a comment below if you end up using this and found it helpful!

Code on web assassins.

Scrolldown Icon