Skip to content

Instantly share code, notes, and snippets.

@Loiree
Created October 9, 2015 23:33
Show Gist options
  • Save Loiree/56ed224a1903532fdcaf to your computer and use it in GitHub Desktop.
Save Loiree/56ed224a1903532fdcaf to your computer and use it in GitHub Desktop.
Phone Mask
# Phone Mask
# маска телефонного номера для input
# IE9+
# --------------------------------------------------------
# cache
# phones — массив input-элементов, которым нужна маска
# setCaret — устанавливает курсор в нужную позицию
# getCaret — получает значение курсора
# mask — функция маскировки
# nums — массив из введенных чисел и _ (без семерки)
# caretPos — позиция курсора в input
# --------------------------------------------------------
PhoneMask = do ->
init: ->
this.cache()
this.bindEvents()
settings: ->
this.caretPos = 4
cache: ->
this.phones = document.getElementsByClassName("phone-mask")
bindEvents: ->
self = this
for i in this.phones then i.addEventListener "click", -> self.mask(this)
for i in this.phones then i.addEventListener "focus", -> self.mask(this)
for i in this.phones then i.addEventListener "keydown", (e) -> self.mask(this, e)
setCaret: ->
if this.caretPos < 4 then this.caretPos = 4
if this.obj.setSelectionRange
this.obj.focus()
this.obj.setSelectionRange(this.caretPos,this.caretPos)
getCaret: ->
if document.selection
this.obj.focus()
Sel = document.selection.createRange()
Sel.moveStart('character', -this.obj.value.length)
this.caretPos = Sel.text.length
else if this.obj.selectionStart || this.obj.selectionStart is "0"
this.caretPos = this.obj.selectionStart
if this.caretPos is undefined then this.caretPos = 4
mask: (obj, e) ->
# Если выбрано другое поле — ставим курсор в начало
if this.obj != obj
this.obj = obj
this.caretPos = 4
this.setCaret()
this.getCaret()
nums = this.obj.value
nums = nums.split("")
for i in [nums.length..0]
if isNaN(nums[i]) or nums[i] is " "
if nums[i] isnt "_"
nums.splice(i, 1)
nums = nums.splice(1,nums.length-1)
if e
if 48 <= e.keyCode <= 57 # если нажата цифра
key = String.fromCharCode(e.keyCode) # нажатая цифра
# Сдвигаем курсор в нужных местах
if this.caretPos is 7
this.caretPos += 2
else if this.caretPos is 12 or this.caretPos is 15
this.caretPos += 1
# Заменяем данные в массиве nums
if this.caretPos is 4 or this.caretPos is 5 or this.caretPos is 6
if nums[this.caretPos-4] is "_"
nums[this.caretPos-4] = key
else if parseInt(nums[this.caretPos-4]) isnt NaN
nums.splice(this.caretPos-4,0,key)
else if this.caretPos is 9 or this.caretPos is 10 or this.caretPos is 11
if nums[this.caretPos-6] is "_"
nums[this.caretPos-6] = key
else if parseInt(nums[this.caretPos-6]) isnt NaN
nums.splice(this.caretPos-6,0,key)
else if this.caretPos is 13 or this.caretPos is 14
if nums[this.caretPos-7] is "_"
nums[this.caretPos-7] = key
else if parseInt(nums[this.caretPos-7]) isnt NaN
nums.splice(this.caretPos-7,0,key)
else if this.caretPos is 16 or this.caretPos is 17
if nums[this.caretPos-8] is "_"
nums[this.caretPos-8] = key
else if parseInt(nums[this.caretPos-8]) isnt NaN
nums.splice(this.caretPos-8,0,key)
# Позиция курсора
if this.caretPos is 6 then this.caretPos += 3
else if this.caretPos is 11 or this.caretPos is 14
this.caretPos += 2
else this.caretPos += 1
# если нажат backspace, переставляем курсор и удаляем
if e.keyCode is 8
e.preventDefault()
if this.caretPos is 5 or this.caretPos is 6 or this.caretPos is 7
nums.splice(this.caretPos-5,1)
this.caretPos -= 1
else if this.caretPos is 9
this.caretPos -= 3
nums.splice(this.caretPos-4,1)
else if this.caretPos is 10 or this.caretPos is 11 or this.caretPos is 12
nums.splice(this.caretPos-7,1)
this.caretPos -= 1
else if this.caretPos is 13
nums.splice(this.caretPos-8,1)
this.caretPos -= 2
else if this.caretPos is 14 or this.caretPos is 15
nums.splice(this.caretPos-8,1)
this.caretPos -= 1
else if this.caretPos is 16
nums.splice(this.caretPos-9,1)
this.caretPos -= 2
else if this.caretPos is 17 or this.caretPos is 18
nums.splice(this.caretPos-9,1)
this.caretPos -= 1
if e.keyCode is 46 # нажат del
e.preventDefault()
if e.keyCode is 37 # стрелка влево
if this.caretPos is 4
e.preventDefault()
else if this.caretPos is 9
this.caretPos -= 1
if e.keyCode is 39 # стрелка вправо
if this.caretPos is 7
this.caretPos += 1
# формируем итоговую строку
newStr = "+7 ("
for i in [0..9]
if isNaN(nums[i]) then newStr += "_"
else newStr += nums[i]
newStr = newStr.slice(0,7) + ") " + newStr.slice(7,10) + "-" + newStr.slice(10,12) + "-" + newStr.slice(12,14)
# Вставляем результат в input и ставим курсор на нужную позицию
obj.value = newStr
this.setCaret()
<input class="phone-mask" type="text" maxlength="18" placeholder=" Введите Ваш телефон">
<input class="phone-mask" type="text" maxlength="18" placeholder=" Введите Ваш телефон">
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment