Masking Input Fields With Alpine.js
To create an input mask with Alpine.js, you will need to use the x-bind and x-on directives to bind a function to the input's keydown event, which will allow you to manipulate the input's value as the user types. Here is an example of an input mask for a phone number:
<input x-bind:value="phoneNumber" x-on:keydown="maskPhoneNumber">
<script>
new Alpine({
data: {
phoneNumber: ''
},
methods: {
maskPhoneNumber(event) {
let x = event.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
event.target.value = !x[2] ? x[1] : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '');
}
}
});
</script>
This will format the input's value as the user types to match the format of a US phone number (e.g. (123) 456-7890).
Example for masking decimal numbers
Here's an example of an input mask for decimal numbers using Alpine.js:
<input x-bind:value="decimalNumber" x-on:keydown="maskDecimalNumber">
<script>
new Alpine({
data: {
decimalNumber: ''
},
methods: {
maskDecimalNumber(event) {
let x = event.target.value.replace(/[^0-9.]/g, '');
event.target.value = x;
}
}
});
</script>
This will only allow numbers and the decimal point to be entered into the input, and will automatically remove any non-numeric characters that are typed. You can specify the number of decimal digits you want to allow by adding .toFixed(n) where n is the number of decimal digits.
event.target.value = parseFloat(x).toFixed(2);
This will allow 2 decimal digits.