Skip to content

Instantly share code, notes, and snippets.

@b-aleksei
Last active November 17, 2020 13:24
Show Gist options
  • Save b-aleksei/064d065430ecef0932509a6141d4d943 to your computer and use it in GitHub Desktop.
Save b-aleksei/064d065430ecef0932509a6141d4d943 to your computer and use it in GitHub Desktop.
PhoneMask
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