why u not using type="date" input or many masked-input package?
What's the best way to automatically insert slashes '/' in date fields
I'm trying to add functionality to input date fields so as when the users enters in digits, slashes "/" get automatically added. (text filed)
<v-text-field
v-model="a"
label="date *"
id="date"
required
></v-text-field>
a: function (data){
var text = this.a || "";
text = text.replace(/\D/g, "");
text = text.replace(/^(\d{2})(\d+)/g, "/");
text = text.replace(/^(\d{2}\/\d{2})(\d{1,4})$/g, "/");
if (/^[\d]{2}\/[\d]{2}\/[\d]{4}$/g.test(text)) {
console.log(this.a)
console.log(text.length)
//this.a.maxLength = text.length;
}
this.a = text;
return this.a
}
I am getting proper date like this 13/13/1212 but it is not validated can any one tell how to validate date
ok, lets do this in 2 step. first, we need validate input and allow input only in our regexp (actually 3 regexp, for full date, month-year and year-only)
<div id="app">
<input :value="date" @input="onInput" />
<div>{{format}}</div>
</div>
const DATE_FORMAT = {
null: new RegExp('^$'),
'full': new RegExp('^[0-9]{1,2}(\/([0-9]{1,2}(\/([0-9]{1,4})?)?)?)?$'),
'month-year': new RegExp('^[0-9]{1,2}(\/([0-9]{1,4})?)?$'),
'year-only': new RegExp('^[0-9]{1,4}$'),
}
const Counter = {
data () {
return {
date: "",
format: "null"
}
},
methods: {
onInput (e) {
let text = e.currentTarget.value || ""
const test = Object.entries(DATE_FORMAT).find(regexp => {
if (regexp[1].test(text)) { // map for regexp, find correct
return regexp[0]
}
})
if (test) { // if regexp find, set `this.date` and `this.format`
this.format = test[0]
this.date = text
}
this.$forceUpdate() // force update for rerender
}
}
}
Vue.createApp(Counter).mount('#app')
now our input always regexp format. next, we need to add slashes. and we must understand on the fly, what the format we need. example, where user inputs 11/11, what we need to do? add slashes? or user want enter 11/1111? for this cases, make new method and enjoy with him. example:
dateAutoSlashes (e) {
if (e.inputType === 'deleteContentBackward') return // if backspace, break.
if (this.date.length === 2) { // add slashes after two digits
this.date = this.date + '/'
}
if (this.date.length === 5 && parseInt(this.date.substr(3)) <= 12) { // add slashes after second two digits only if his lower than
this.date = this.date + '/'
}
}
and call it from onInput, after this.date = text
u can play with both steps on
https://codepen.io/trin4ik/pen/NWbXEMV?editors=1010 step 1 https://codepen.io/trin4ik/pen/GRNywGX?editors=1010 step 2
Please or to participate in this conversation.