Implementing Input Masking in a Vue.js Application: Input masking is a technique used to enforce a specific format for user input in text fields, such as dates, phone numbers, and credit card numbers.In this tutorial we will learn how to implement input masking in a Vue.js application
How to Implement Input Masking in Vue.js?
The given code is a Vue.js application which performs the following actions:
- HTML Template:
- A div is created with an ID of “app”, which contains an input field for entering a phone number.
- The input field is bound to a data property “formattedPhoneNumber” using the v-model directive.
- An @input event is attached to the input field that triggers the “formatPhoneNumber” method.
- JavaScript Code:
- A new instance of Vue is created, which consists of:
- el: A string that specifies the div with ID “app” as the element that the Vue app is bound to.
- data: An object containing two properties, “rawPhoneNumber” and “formattedPhoneNumber”, used to store the phone number entered by the user.
- methods: An object containing two methods:
- formatPhoneNumber: This method takes the current value of the input field and updates the “rawPhoneNumber” data property with it. It then formats the “formattedPhoneNumber” using the “formatAsPhoneNumber” method.
- formatAsPhoneNumber: This method takes the value of “rawPhoneNumber”, removes all non-numeric characters, limits it to 10 characters, and formats it as -XXX- XXX-XXXX.
- A new instance of Vue is created, which consists of:
The user can enter a phone number in the input field, and the app will automatically format it as XXX- XXX-XXXX.
Implementing Input Masking in Vue.js
<div id="app">
<input type="text" class="custom-input" v-model="formattedPhoneNumber" @input="formatPhoneNumber"
placeholder="Enter Phone Number" />
</div>
<script type="module">
const app = new Vue({
el: "#app",
data() {
return {
rawPhoneNumber: '',
formattedPhoneNumber: ''
}
},
methods: {
formatPhoneNumber(event) {
this.rawPhoneNumber = event.target.value;
this.formattedPhoneNumber = this.formatAsPhoneNumber(this.rawPhoneNumber);
},
formatAsPhoneNumber(value) {
value = value.replace(/\D/g, '');
if (value.length > 10) {
value = value.slice(0, 10);
}
value = value.slice(0, 3) + '-' + value.slice(3, 6) + '-' + value.slice(6);
return value;
}
}
});
</script>