0

I am trying to make a textbox that only allows numbers and shows a specific markup like this: ____ ____ ____ _ and when you type something it should change to 1234 56__ ____ _ . I figured out i could make the textbox accept only numbers underscores and spaces by using the following javascript code.

<input id="code"
onkeyup="document.getElementById('code').value = document.getElementById('code').value.replace(/[^0-9_ ]+/g, '');" />

this allows me to only type numbers underscores and spaces, but I am having problems with grouping the characters and separating them with spaces and displaying the underscores correctly. Anybody knows how I could achieve the preferred result? Thanks in advance.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • Perhaps you want to look at this question: https://stackoverflow.com/questions/30058927/format-a-phone-number-as-a-user-types-using-pure-javascript – soktinpk Oct 07 '18 at 16:30
  • thanks a lot! I managed to do what i wanted to with the help of that question! – Adrian Belmans Oct 07 '18 at 17:45

1 Answers1

0

I managed to solve this using https://jsfiddle.net/rafj3md0/

HTML

<input id="phoneNumber" maxlength="16" />

JavaScript (ES6)

const isNumericInput = (event) => {
    const key = event.keyCode;
    return ((key >= 48 && key <= 57) || // Allow number line
        (key >= 96 && key <= 105) // Allow number pad
    );
};

const isModifierKey = (event) => {
    const key = event.keyCode;
    return (event.shiftKey === true || key === 35 || key === 36) || // Allow Shift, Home, End
        (key === 8 || key === 9 || key === 13 || key === 46) || // Allow Backspace, Tab, Enter, Delete
        (key > 36 && key < 41) || // Allow left, up, right, down
        (
            // Allow Ctrl/Command + A,C,V,X,Z
            (event.ctrlKey === true || event.metaKey === true) &&
            (key === 65 || key === 67 || key === 86 || key === 88 || key === 90)
        )
};

const enforceFormat = (event) => {
    // Input must be of a valid number format or a modifier key, and not longer than ten digits
    if(!isNumericInput(event) && !isModifierKey(event)){
        event.preventDefault();
    }
};

const formatToPhone = (event) => {
    if(isModifierKey(event)) {return;}

    // I am lazy and don't like to type things more than once
    const target = event.target;
    const input = event.target.value.replace(/\D/g,'').substring(0,10); // First ten digits of input only
    const zip = input.substring(0,3);
    const middle = input.substring(3,6);
    const last = input.substring(6,10);

    if(input.length > 6){target.value = `(${zip}) ${middle} - ${last}`;}
    else if(input.length > 3){target.value = `(${zip}) ${middle}`;}
    else if(input.length > 0){target.value = `(${zip}`;}
};

const inputElement = document.getElementById('phoneNumber');
inputElement.addEventListener('keydown',enforceFormat);
inputElement.addEventListener('keyup',formatToPhone);