|
26 | 26 | .formatToParts(1.1) |
27 | 27 | .find(part => part.type === 'decimal') |
28 | 28 | .value; |
29 | | - const digits = '0123456789'; |
| 29 | + |
| 30 | + const digits = [ |
| 31 | + '0', |
| 32 | + '1', |
| 33 | + '2', |
| 34 | + '3', |
| 35 | + '4', |
| 36 | + '5', |
| 37 | + '6', |
| 38 | + '7', |
| 39 | + '8', |
| 40 | + '9', |
| 41 | + ]; |
| 42 | + |
| 43 | + const allowedKeys = [ |
| 44 | + 'ArrowDown', |
| 45 | + 'ArrowLeft', |
| 46 | + 'ArrowRight', |
| 47 | + 'ArrowUp', |
| 48 | + 'Backspace', |
| 49 | + 'Delete', |
| 50 | + 'End', |
| 51 | + 'Enter', |
| 52 | + 'Home', |
| 53 | + 'PageDown', |
| 54 | + 'PageUp', |
| 55 | + 'Tab', |
| 56 | + ]; |
30 | 57 |
|
31 | 58 | function getElementLang(element) { |
32 | 59 | if (element.lang) { |
|
50 | 77 | .value; |
51 | 78 | } |
52 | 79 |
|
53 | | - element.addEventListener('keydown', function (event) { |
54 | | - if (event.key === 'Backspace' || '0123456789'.indexOf(event.key) !== -1) { |
55 | | - return; |
| 80 | + function isCharAllowed(char) { |
| 81 | + if (digits.includes(char)) { |
| 82 | + return true; |
56 | 83 | } |
57 | 84 |
|
58 | | - if ('-' === event.key) { |
59 | | - if (element.value.indexOf('-') === -1 && (element.min < 0 || element.min === '' || element.min == null)) { |
60 | | - return; |
| 85 | + if ('-' === char) { |
| 86 | + if (!element.value.includes('-') && (element.min < 0 || element.min === '' || element.min == null)) { |
| 87 | + return true; |
61 | 88 | } |
62 | 89 | } |
63 | | - else if (decimalSeparators.indexOf(event.key) !== -1) { |
64 | | - if (element.value.indexOf('.') === -1 && (element.step === 'any' || element.step < 1)) { |
65 | | - return; |
| 90 | + else if (decimalSeparators.includes(char)) { |
| 91 | + if (!element.value.includes('.') && (element.step === 'any' || element.step < 1)) { |
| 92 | + return true; |
66 | 93 | } |
67 | 94 | } |
68 | 95 |
|
69 | | - event.preventDefault(); |
| 96 | + return false; |
| 97 | + } |
| 98 | + |
| 99 | + element.addEventListener('keydown', function (event) { |
| 100 | + if (!event.ctrlKey && !allowedKeys.includes(event.key) && !isCharAllowed(event.key)) { |
| 101 | + event.preventDefault(); |
| 102 | + } |
| 103 | + }); |
| 104 | + |
| 105 | + element.addEventListener('paste', function (event) { |
| 106 | + const data = event.clipboardData.getData('text/plain'); |
| 107 | + if (data === '') { |
| 108 | + event.preventDefault(); |
| 109 | + return; |
| 110 | + } |
| 111 | + |
| 112 | + for (let i = 0; i < data.length; i++) { |
| 113 | + if (!isCharAllowed(data[i])) { |
| 114 | + event.preventDefault(); |
| 115 | + |
| 116 | + return; |
| 117 | + } |
| 118 | + } |
70 | 119 | }); |
71 | 120 | }); |
72 | 121 | } |
|
0 commit comments