I have a text field containing the date value in (MM/DD/YYYY) format. Whenever I type 01242022, it should be autoformatted and shown as 01/24/2022. I tried the following way where the value is shown as expected, but I want it in real-time. This is working when we change the focus of the input element. Any help is appreciated. Thanks
Vue.filter("formatDate", function (value) {
let dateValue = value;
if (dateValue.length === 2 || dateValue.length === 5) {
dateValue = value + "/";
}
return dateValue;
});
const app = new Vue({
el: "#app",
data() {
return {
date: new Date(),
};
},
computed: {
dateVal: {
get() {
// eslint-disable-next-line no-extra-boolean-cast
if (!!this.date) return moment(this.date, "MMDDYYYY").format("L");
return this.date;
},
set(value) {
this.date = moment(value, "MMDDYYYY").format("L");;
},
},
},
methods: {
onInput(e) {
this.dateVal = this.$options.filters.formatDate(e.target.value);
},
},
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<div id="app">
<input
type="text"
v-model.lazy="dateVal"
maxlength="10"
/>
</div>