Practical Use of Alpine.js Mask Plugin: Real World Example

Practical Use of Alpine.js Mask Plugin: Real World Example

Realm Coding

6 min read

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

โผป The problem

The Solution in code for the impatient

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:

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

we get the following form submission error:

Sudorealm become an author feature form error

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

โผป 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.

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 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:

x-mask:dynamic="addHttps($input)"
<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:

    <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

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.

๐Ÿš€ Spread the Love & Support the Realm

Hey there, fellow Realmer! If this guide illuminated a new path in your coder/hacker journey, your support would mean a lot. Every bit of magic helps.

Spread the Love

๐Ÿ‘‘ Crown & Share: If you found value in this post, please give it a crown and share it with your fellow coder/hacker enthusiasts. Spreading knowledge is what Sudorealm is all about! Fun fact the Author with the most crowns inside a realm will be crowned as the Realm King! ๐Ÿคด

๐Ÿ†‡ X Shoutout: Feeling extra grateful or have some cool feedback? Drop me a shoutout on Twitter โ€“ I'd love to hear from you! d3adR1nger on X

๐Ÿ’ฌ Join our Discord Server: Join the Sudorealm Discord Server connect with fellow enthusiasts and chat about everything that fascinates you! From new blog post suggestions to seeking support on tricky tutorials. Come, share your ideas, and let's grow together! ๐Ÿš€๐ŸŒ

Support the Realm

๐Ÿ› Affiliate Treasures Below: Dive into the depths below the post to uncover some affiliate products I've curated just for you. It's a great way to support the realm and discover some nerdy treasures.

โ˜•๏ธ Coffee Driven Development: Love what you're reading? Fuel my passion for coding with a delicious cup of coffee! Every sip powers up another line of code and helps bring more exciting content your way. Support my caffeine-fueled coding adventures and let's brew up something amazing together! โ˜•๐Ÿ‘จโ€๐Ÿ’ป Join the journey and BuyMeACoffee

Thanks for being a part of our realm. Every bit of support propels our community to new horizons. Until next time, keep exploring!

Affiliate Links

Check out what d3ad R1nger suggests for Practical Use of Alpine.js Mask Plugin: Real World Example!

Ready to Forge an Alliance
๐Ÿค

Join our alliance and play a pivotal role in the evolution of our digital realm! By aligning with our pricing model, you're not just accessing premium features; you're becoming an integral part of our journey. As an ally, your support propels us forward, ensuring we continue to innovate and thrive.

Lifetime membership

As valued allies, exclusive content awaits you ๐Ÿ‘€. Unlock a suite of premium features and gain early access to ally-only enhancements in our realm. With our month-by-month commitment, you're always privy to our most coveted updates!

What's included

  • Premium Content Access
  • Ally resources + Unique Ally Badge
  • Access to Affiliate store front ๐Ÿค‘ (๐Ÿ”ฎ)
  • More to come...

It's like buying a pint ๐Ÿบ. But less!

โ‚ฌ1.99 EUR

Forge Alliance

Invoices and receipts available for easy company reimbursement

Subscribe to our newsletter.

๐Ÿ‘‹ Hey there, Realmer! Fancy getting a byte of nerdy knowledge straight to your inbox? Subscribe to our Sudorealm newsletter and don't miss a single trick from our growing community of curious minds! Ready to level up your knowledge game? Join us in the Realm today!

Be one of the privileged few
Think of it as your VIP pass into the Realm where you'll get first dibs on new features, insider updates, and more.
No spam
And, worry not, we promise not to spam โ€“ just top-tier, brain-tickling content.