Vue Js Input Mask for Credit Card:To create a credit card input mask in Vue.js without using a library, you can utilize computed properties and v-model directive. First, define a computed property that formats the input value based on the desired credit card pattern. Use the v-model directive to bind the input field to this computed property. Inside the computed property, use string manipulation and regular expressions to format the value with appropriate spaces and dashes. Finally, handle any additional logic such as limiting the input length or validating the credit card number.
How can I implement an input mask for credit card numbers using Vue.js?
The provided code demonstrates the implementation of an input mask for credit card numbers using Vue.js. The HTML code includes an input element with a placeholder value representing the desired format for the credit card number. The input element is bound to the creditCardNumber
data property using v-model
, which enables two-way data binding.
In the JavaScript section, the Vue instance is created and attached to the element with the ID “app”. The Vue instance contains the creditCardNumber
data property, which holds the value of the input field. Two methods are defined within the Vue instance: formatCreditCardNumber
and handleKeyDown
.
The formatCreditCardNumber
method is triggered whenever the input value changes. It utilizes regular expressions to remove non-digit characters (\D
) from the creditCardNumber
string and then adds a space after every four characters using the replace
function. The resulting string is then trimmed to remove any leading or trailing whitespace.
The handleKeyDown
method is triggered when a key is pressed within the input field. It prevents any key other than digits, Backspace, or Delete from being entered by calling event.preventDefault()
.
Overall, this implementation ensures that the credit card number input is formatted correctly and restricts the input to only accept valid characters.
Vue Js Input Mask for Credit Card Example
<div id="app">
<input type="text" placeholder='####-####-####-####' v-model="creditCardNumber" class="custom-input" @input="formatCreditCardNumber" @keydown="handleKeyDown">
</div>
<script type="module">
const app = new Vue({
el: "#app",
data: {
creditCardNumber: ''
},
methods: {
formatCreditCardNumber() {
this.creditCardNumber = this.creditCardNumber.replace(/\D/g, '').replace(/(.{4})/g, '$1 ').trim();
},
handleKeyDown(event) {
if (!/^\d$|^Backspace$|^Delete$/.test(event.key)) {
event.preventDefault();
}
}
}
});
</script>