Last active
November 17, 2020 13:24
-
-
Save b-aleksei/064d065430ecef0932509a6141d4d943 to your computer and use it in GitHub Desktop.
PhoneMask
This file contains 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
const COUNTRY_CODE = 7; | |
const onInputPhoneInput = ({target}) => { | |
const matrix = `+${COUNTRY_CODE} (___) ___-__-__`; | |
let counter = 0; | |
let val = target.value.replace(/\D/g, ''); | |
if (!val.length) { | |
val = `${COUNTRY_CODE}`; | |
} | |
target.value = ''; | |
Array.prototype.forEach.call(matrix, (item) => { | |
let isValNumber = /[_\d]/.test(item) && val.length > counter; | |
if (isValNumber) { | |
target.value += val.charAt(counter++); | |
} else { | |
target.value += val.length <= counter ? '' : item; | |
} | |
}); | |
}; | |
const onFocusPhoneInput = (target) => { | |
if (!target.value) { | |
target.value = `+${COUNTRY_CODE}`; | |
} | |
target.addEventListener('input', onInputPhoneInput); | |
target.addEventListener('blur', onBlurPhoneInput); | |
}; | |
const onBlurPhoneInput = ({target}) => { | |
if (target.value === `+${COUNTRY_CODE}`) { | |
target.value = ''; | |
} | |
target.removeEventListener('input', onInputPhoneInput); | |
target.removeEventListener('blur', onBlurPhoneInput); | |
}; | |
export default onFocusPhoneInput; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment