Reputation: 1761
I want to enable text box to take formatting while tying telephone number into textbox.
Upvotes: 3
Views: 6617
Reputation: 2937
Given that the question doesn't have a lot of information on what has been tried or how to achieve it I'll just make a common component that you can reuse for later.
What you can do it with a watcher and a regexp on the field that formats the number to what you want to display
Vue.component('my-phone-input', {
template: `
<div>
<input type="text" v-model="formattedPhoneValue" @keyup="focusOut" @blur="focusOut"/>
</div>`,
data: function() {
return {
phoneValue: 0,
formattedPhoneValue: "0",
preventNextIteration: false
}
},
methods: {
focusOut: function(event) {
if (['Arrow', 'Backspace', 'Shift'].includes(event.key)) {
this.preventNextIteration = true;
return;
}
if (this.preventNextIteration) {
this.preventNextIteration = false;
return;
}
this.phoneValue = this.formattedPhoneValue.replace(/-/g, '').match(/(\d{1,10})/g)[0];
// Format display value based on calculated currencyValue
this.formattedPhoneValue = this.phoneValue.replace(/(\d{1,3})(\d{1,3})(\d{1,4})/g, '$1-$2-$3');
}
}
});
new Vue({
el: '#app'
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
<my-phone-input></my-phone-input>
</div>
Upvotes: 5