Mask input field for US numbers with editing

PHOTO EMBED

Thu Nov 25 2021 11:17:10 GMT+0000 (UTC)

Saved by @programarina #typescript #javascript

// Example 4051231234 -> (405) 123-1234
export const formatToUSPhoneNumber = (e: React.ChangeEvent<HTMLInputElement>): string => {
  const phoneField = e.target;

  const cursorPosition = phoneField.selectionStart;
  const numericString = phoneField.value.replace(/\D/g, '').substring(0, 10);

  const match = numericString.match(/^(\d{1,3})(\d{0,3})(\d{0,4})$/);

  if (match) {
    let newVal = '(' + match[1];
    newVal += match[2] ? ') ' + match[2] : '';
    newVal += match[3] ? '-' + match[3] : '';

    // to help us put the cursor back in the right place
    const delta = newVal.length - Math.min(phoneField.value.length, 14);
    phoneField.value = newVal;
    if (cursorPosition) {
      phoneField.selectionEnd = cursorPosition + delta;
    }
  } else {
    phoneField.value = '';
  }

  return phoneField.value;
};
content_copyCOPY