forked from alexey-goloburdin/phoneinput
-
Notifications
You must be signed in to change notification settings - Fork 0
/
phoneinput.js
76 lines (70 loc) · 2.93 KB
/
phoneinput.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
document.addEventListener("DOMContentLoaded", function () {
var phoneInputs = document.querySelectorAll('input[data-tel-input]');
var getInputNumbersValue = function (input) {
// Return stripped input value — just numbers
return input.value.replace(/\D/g, '');
}
var onPhonePaste = function (e) {
var input = e.target,
inputNumbersValue = getInputNumbersValue(input);
var pasted = e.clipboardData || window.clipboardData;
if (pasted) {
var pastedText = pasted.getData('Text');
if (/\D/g.test(pastedText)) {
// Attempt to paste non-numeric symbol — remove all non-numeric symbols,
// formatting will be in onPhoneInput handler
input.value = inputNumbersValue;
return;
}
}
}
var onPhoneInput = function (e) {
var input = e.target,
inputNumbersValue = getInputNumbersValue(input),
selectionStart = input.selectionStart,
formattedInputValue = "";
if (!inputNumbersValue) {
return input.value = "";
}
if (input.value.length != selectionStart) {
// Editing in the middle of input, not last symbol
if (e.data && /\D/g.test(e.data)) {
// Attempt to input non-numeric symbol
input.value = inputNumbersValue;
}
return;
}
if (["7", "8", "9"].indexOf(inputNumbersValue[0]) > -1) {
if (inputNumbersValue[0] == "9") inputNumbersValue = "7" + inputNumbersValue;
var firstSymbols = (inputNumbersValue[0] == "8") ? "8" : "+7";
formattedInputValue = input.value = firstSymbols + " ";
if (inputNumbersValue.length > 1) {
formattedInputValue += '(' + inputNumbersValue.substring(1, 4);
}
if (inputNumbersValue.length >= 5) {
formattedInputValue += ') ' + inputNumbersValue.substring(4, 7);
}
if (inputNumbersValue.length >= 8) {
formattedInputValue += '-' + inputNumbersValue.substring(7, 9);
}
if (inputNumbersValue.length >= 10) {
formattedInputValue += '-' + inputNumbersValue.substring(9, 11);
}
} else {
formattedInputValue = '+' + inputNumbersValue.substring(0, 16);
}
input.value = formattedInputValue;
}
var onPhoneKeyDown = function (e) {
// Clear input after remove last symbol
var inputValue = e.target.value.replace(/\D/g, '');
if (e.keyCode == 8 && inputValue.length == 1) {
e.target.value = "";
}
}
for (var phoneInput of phoneInputs) {
phoneInput.addEventListener('keydown', onPhoneKeyDown);
phoneInput.addEventListener('input', onPhoneInput, false);
phoneInput.addEventListener('paste', onPhonePaste, false);
}
})