Practical Use of Alpine.js Mask Plugin: Real World Example
Tags: alpinejs, laravel, maskplugin, frontend
Published: 2023-12-11 10:40:21

Recently, while working on a new feature for Sudorealm, I encountered a seemingly minor issue with an input field. It turned out to be a great learning opportunity, and I'm excited to share this experience with you. 

I was developing a new modal form for Sudorealm users aspiring to become authors on the platform. This form included a section with three input fields for users to list any articles they've previously written, if applicable. At first, I didn’t think much of it. But when I reached the stage where I needed to validate the data, I realized a small, yet significant problem had arisen. Let me show you what I am talking about. 

![Sudorealm become an author feature](https://i.postimg.cc/SKn3Q4C5/Screenshot-2023-12-11-at-9-47-30-AM.png)

## ⼻ The problem
[The Solution in code for the impatient](#implementation)

This is the modal form that I am talking about, it's pretty straightforward to fill up. But when we use the following Laravel Livewire validation:

```php
'sudoerForm.primary_article.*' => ['nullable', 'url', 'max:255'],
```

we get the following form submission error: 

![Sudorealm become an author feature form error](https://i.postimg.cc/kMQZgfRn/Screenshot-2023-12-11-at-9-51-48-AM.png)

As you have observed the form error appears only on the first input and not on the second one. Why is that? This is because Laravel's `url`  validation error accepts only URLs with `https://` or `http://` upfront. 

Initially, my plan was to leave the URL input as it was, assuming users would usually paste their URLs, including the `https://` part. But then, a thought struck me, inspired by the 'broken-window theory'* I read about in 'The Pragmatic Programmer': Could this be a 'broken window' in my code? By leaving it as is, was I setting myself up for future issues? Conversely, if I address it now, could this fix potentially prevent similar problems in other, yet-to-be-updated parts of my code? Therefore I decided to come up with a cool and breezy solution! 

![Sudorealm coding session thumbs up](https://media1.tenor.com/m/YbmQHDSJvbkAAAAC/thumbs-up-hacker.gif)

## ⼻ The Solution 

Alpine.js to the rescue!!! A lightweight JavaScript framework that's easy to use yet surprisingly powerful. It brings reactivity and data-binding to your HTML, similar to Vue.js, but with a simpler, more direct approach. It's perfect for quickly adding interactivity to web pages without the complexity of heavier frameworks. From the mind of [Caleb Porzio](https://twitter.com/calebporzio).

This crazy useful library also provides plugins, and other stuff ( but we kinda want to focus on the plugins 🤪). Alpine.js Plugins extend the core functionality of Alpine.js, allowing developers to easily integrate additional features without bloating their code. They're perfect for when you need that extra functionality without the overhead of a larger framework.

Zooming in on one particular Alpine.js Plugin that's central to our discussion: the **Mask Plugin**. The Mask Plugin is a nifty tool that simplifies the handling of user input formatting. Whether you're dealing with phone numbers, dates, or in our case, **URLs**, it ensures that the input matches a specific pattern, enhancing both data consistency and user experience. It's a straightforward yet powerful solution that elegantly addresses common input-related challenges, like the one I encountered with URL validation. Take a look at the [documentation](https://alpinejs.dev/plugins/mask) as well. 

### 🎯 Objective
My goal was straightforward: I wanted the `https://` to automatically appear whenever a user started typing a URL in the input field. Reading a bit into the documentation of the plugin I realized that what I wanted to achieve was a dynamic mask. Once this was clear, implementing the solution was a breeze.

### 🔨 Implementation

Here’s how it’s done:
```html
x-mask:dynamic="addHttps($input)"
```
```html
<x-input.minimal.text x-mask:dynamic="addHttps($input)" wire:model.defer="livewire.name.of.model" />
```

In the HTML (blade component, in my case), we use the `x-mask:dynamic` attribute from the Mask Plugin. This attribute calls the `addHttps` function, which we define in JavaScript:

```js
    <script>
        function addHttps(input) {
            if (!input.startsWith('https://')) {
                return 'https://' + input;
            }
            return input;
        }
    </script>
```

This JavaScript function, `addHttps`, checks if the input begins with `https://`. If not, it automatically prepends this to the user's input. It’s a simple yet elegant solution to ensure URLs are formatted correctly right from the start.

### Result
The final result looks something like this: 

![Alpine.js Mask Plugin for URLs, by sudorealm](https://i.postimg.cc/4317dCG6/alpinemaskplugin.gif)

What's even cooler is that it also works when you paste entire URLs without the `https://` prefix. You should definitely give it a try on your Alpine.js projects. 

## Conclusion
And there you have it — a seamless integration of the Alpine.js Mask Plugin to elegantly solve a common URL input formatting issue. The final result, as demonstrated, not only enhances user experience by automatically adding 'https://' to URL inputs but also maintains a clean and consistent data format. This practical example showcases the power of Alpine.js in simplifying complex problems with minimal code, affirming its utility in web development.

Remember, the beauty of Alpine.js and its plugins lies in their simplicity and efficiency. By exploring and implementing such tools, we can create more intuitive and user-friendly web applications. I hope this example from Sudorealm inspires you to experiment with Alpine.js in your projects and discover the many ways it can streamline your development process.

---

### You are invited to the party! 🎉

If you found this guide on using the Alpine.js Mask Plugin helpful, there's plenty more where that came from! I invite you to join [Sudorealm](https://sudorealm.com/register), an aspiring Nerdom with article topics ranging from the world of gaming, anime, and manga to the intricate realms of coding and hacking