Skip to content

Instantly share code, notes, and snippets.

@Maxim-Kolmogorov
Last active November 11, 2022 09:13
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Maxim-Kolmogorov/d867767c976532fea60ee4a1abd725e7 to your computer and use it in GitHub Desktop.
Save Maxim-Kolmogorov/d867767c976532fea60ee4a1abd725e7 to your computer and use it in GitHub Desktop.
Phone mask with Vue.js
import Vue from "vue"
Vue.directive('phone', {
bind(el) {
el.oninput = function(e) {
if (!e.isTrusted) {
return
}
const x = this.value.replace(/\D/g, '').match(/(\d{0,1})(\d{0,3})(\d{0,3})(\d{0,4})/)
if (!x[2] && x[1] !== '') {
this.value = x[1] === '8' ? x[1] : '8' + x[1]
} else {
this.value = !x[3] ? x[1] + x[2] : x[1] + '(' + x[2] + ') ' + x[3] + (x[4] ? '-' + x[4] : '')
}
}
},
})
@Siwaaa
Copy link

Siwaaa commented Aug 31, 2022

Чтобы первый символ ввода, отличный от 7 и 8, сразу попадал в input, для маски +7 (999) 999-99-99 вместо x[1] = '+7' можно вставить:

if(x[1] === '7' || x[1] === '8') {
  x[1] = '+7'
} else {
  x[2] = x[1]
  x[1] = '+7'
}

@spokik
Copy link

spokik commented Nov 4, 2022

автозаполнение от браузеров не вызывает onpaste() Я на onchange() повесил, но подозреваю можно все и через oninput() слушать

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment