带有JavaScript的JavaScript文本框自定义模式/标记

时间:2018-10-07 14:53:02

标签: javascript

我正在尝试制作一个仅允许数字并显示特定标记的文本框,如下所示:____ ____ ____ _,当您键入内容时应更改为1234 56__ ____ _。我发现我可以使用以下JavaScript代码使文本框仅接受数字下划线和空格。

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

这使我只能键入数字下划线和空格,但是在对字符进行分组并将其与空格分开并正确显示下划线时遇到了问题。有人知道我如何能达到理想的结果吗?预先感谢。

1 个答案:

答案 0 :(得分:0)

我设法使用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);