Skip to content

Instantly share code, notes, and snippets.

@earthboundkid
Last active October 25, 2019 14:51
Show Gist options
  • Save earthboundkid/0fe5efb56bab070de2222e5c0c347072 to your computer and use it in GitHub Desktop.
Save earthboundkid/0fe5efb56bab070de2222e5c0c347072 to your computer and use it in GitHub Desktop.
<template>
<div id="app">
Value is "{{ value }}". <br />
<input v-model="value" @input="handleChange($event)" />
</div>
</template>
<script>
function trimAndSpace(val) {
return val
.replace(/\D/gi, "")
.replace(/(.{4})/g, "$1 ")
.trim();
}
export default {
name: "App",
data() {
return {
value: "",
lastValue: ""
};
},
methods: {
handleChange(event) {
const lastValueLength = this.lastValue.length;
const curValueLength = this.value.length;
this.lastValue = this.value;
// handle backspace event
if (curValueLength < lastValueLength) {
return;
}
const el = event.target;
const startPos = el.selectionStart;
this.value = trimAndSpace(this.value);
// handle value-edit event
if (startPos < curValueLength) {
this.$nextTick(() => {
el.focus();
el.setSelectionRange(startPos, startPos);
});
}
}
}
};
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment