Phone mask with Vue.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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] : '') | |
} | |
} | |
}, | |
}) |
const x = this.value.replace(/\D/g, '').match(/(\d{0,1})(\d{0,3})(\d{0,3})(\d{0,2})(\d{0,2})/) x[1] = '+7' this.value = !x[3] ? x[1] + ' (' + x[2] : x[1] + ' (' + x[2] + ') ' + x[3] + (x[4] ? '-' + x[4] : '') + (x[5] ? '-' + x[5] : '')
+7 (999) 999-99-99 - я думаю в таком виде, мы чаще видим маски
Чтобы первый символ ввода, отличный от 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'
}
автозаполнение от браузеров не вызывает onpaste() Я на onchange() повесил, но подозреваю можно все и через oninput() слушать
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Это на случай если происходит событие onpaste и вставляется номер, который начинается с 7/+7.