Last active
May 19, 2024 12:56
-
-
Save vaban-ru/aeab582946e1abbb3e060b9c4c5d6992 to your computer and use it in GitHub Desktop.
Универсальная маска для России с помощью iMask.js
This file contains hidden or 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
| // ДЕМО: https://codepen.io/vtboren/pen/ZdGRXp | |
| // Подключаем скрипт маски https://unmanner.github.io/imaskjs/ | |
| // Функция маски | |
| // Работает сразу на все поля с типом поля tel | |
| function initPhoneMask() { | |
| $('input[type=tel]').each(function(index, element) { | |
| var mask = IMask(element, { | |
| mask: [ | |
| { | |
| mask: '+{7} (000) 000-00-00', | |
| country: 'Russia', | |
| startsWith: '8', | |
| prepare: (appended, masked) => { | |
| if (appended === '8' && masked.value === '') { | |
| return '7' | |
| } | |
| return appended | |
| }, | |
| }, | |
| { | |
| mask: '+7 (000) 000-00-00', | |
| startsWith: '+7', | |
| country: 'Russia', | |
| }, | |
| { | |
| mask: '+7 (000) 000-00-00', | |
| startsWith: '7', | |
| country: 'Russia', | |
| }, | |
| { | |
| mask: '+7 (000) 000-00-00', | |
| startsWith: '', | |
| country: 'unknown', | |
| }, | |
| ], | |
| dispatch: function(appended, dynamicMasked) { | |
| var number = (dynamicMasked.value + appended).replace(/\D/g, ''); | |
| return dynamicMasked.compiledMasks.find(function(m) { | |
| return number.indexOf(m.startsWith) === 0; | |
| }); | |
| }, | |
| }); | |
| $(this).blur(function() { | |
| var maskValue = mask.unmaskedValue; | |
| var startWith = 10; | |
| if (maskValue.charAt(0) == '8') { | |
| startWith = 11; | |
| } | |
| if (maskValue.length < startWith) { | |
| mask.value = ''; | |
| } | |
| }); | |
| }); | |
| } | |
| // В битриксе что бы маска инициализировалась после отправки формы аяксом, необходимо поместить функцию вот так: | |
| BX.ready(function() { | |
| BX.addCustomEvent('onAjaxSuccess', function() { | |
| initPhoneMask(); | |
| }); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment