Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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] : '')
}
}
},
})
@Maxim-Kolmogorov

This comment has been minimized.

Copy link
Owner Author

@Maxim-Kolmogorov Maxim-Kolmogorov commented Jan 31, 2021

Это на случай если происходит событие onpaste и вставляется номер, который начинается с 7/+7.

Vue.directive('phone', {
    bind(el) { 
      function replaceNumberForInput(value) {
        let val = ''
        const x = value.replace(/\D/g, '').match(/(\d{0,1})(\d{0,3})(\d{0,3})(\d{0,4})/)

        if (!x[2] && x[1] !== '') {
          val = x[1] === '8' ? x[1] : '8' + x[1]
        } else {
          val = !x[3] ? x[1] + x[2] : x[1] + '(' + x[2] + ') ' + x[3] + (x[4] ? '-' + x[4] : '')
        }

        return val
      }

      function replaceNumberForPaste(value) {
        const r = value.replace(/\D/g, '')
        let val = r
        if (val.charAt(0) === '7') {
          val = '8' + val.slice(1)
        }
        return replaceNumberForInput(val)
      }

      el.oninput = function(e) {
        if (!e.isTrusted) {
          return
        }
        this.value = replaceNumberForInput(this.value)
      }

      el.onpaste = function() {
        setTimeout(() => {
          const pasteVal = el.value
          this.value = replaceNumberForPaste(pasteVal)
        })
      }

    }
})
@egoson

This comment has been minimized.

Copy link

@egoson egoson commented Feb 12, 2021

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 - я думаю в таком виде, мы чаще видим маски

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