简体   繁体   English

如何使用Javascript防止在输入上输入除数字以外的其他字符

[英]How can I prevent other characters from being inputted on an input except numbers using Javascript

I am using Vue.JS (Bootstrap-Vue) to build a form, my input has the following code:我正在使用 Vue.JS (Bootstrap-Vue) 来构建一个表单,我的输入有以下代码:

<b-form-input
            v-mask="'####'"
            number
            type="number"
            no-wheel
            pattern="[0-9]"
            step="1"
            :class="{ 'hasError': $v.form.dobYear.$error }"
            v-model.number="$v.form.dobYear.$model"
            class="form-input"
            name="year"
            id="year"
            maxlength="4"
            min="1900"
            max="2020"
            @keydown="filterKey"
          ></b-form-input>

When a user presses down I want to prevent more than 4 characters to be entered, this works, but when testing, I can see period and dashes and other similar characters can also be added into the input and ignores the maximum of 4 characters .当用户按下时,我想防止输入超过4 个字符,这是可行的,但是在测试时,我可以看到句点和破折号以及其他类似的字符也可以添加到输入中并忽略最多4 个字符 How can I update the following code to ensure nothing but numbers can be added to my input on mobile.如何更新以下代码以确保只能将数字添加到我在移动设备上的输入中。 I'm trying to detect if any of those unwanted keys are pressed then prevent the default action.我试图检测是否按下了任何不需要的键,然后阻止默认操作。 (I've tested on Android Chrome) (我已经在 Android Chrome 上测试过)

filterKey(e) {
      const value = e.target.value;
      const key = e.key;
      console.log(value, this.amount);
      if (String(value).length === 4) {
        //check if a number is pressed after 4 have been entered
        if (!isNaN(Number(key))) {
          e.preventDefault();
          return;
        } else if (key == 190 || key == 189 || key == 107 || key == 69) {
          e.preventDefault();
          return;
        }
      }
    }

The following snippet will not allow anything to be entered into the input element if the length of the input's value is already 4, or if a non-numeric character is typed (but will allow 'Backspace' and 'Delete' keys):如果输入值的长度已经是 4,或者输入了非数字字符(但允许使用“Backspace”和“Delete”键),则以下代码段将不允许在 input 元素中输入任何内容:

EDIT : Implemented Hiws' suggestion to let the user type in numbers even if the length is 4, if some text is selected in the input element编辑:如果在输入元素中选择了某些文本,则实施 Hiws 的建议,即使长度为 4,也允许用户输入数字

function filterKey(e) {
    let previousValue = e.target.value;
    let key = e.keyCode || e.charCode;
    if (key != 8 && key != 46) { // Ignore backspace and delete
        if (
            // preventDefault if length of input is 4 and no text is selected in the input
            ( String(e.target.value).length >= 4 && e.target.selectionStart === e.target.selectionEnd ) ||
            // preventDefault if entered a space or non-number
            !e.key.trim() || isNaN(e.key)
            ) {
            // Prevent input if input length crosses 4,
            // or if input is not a number
            e.preventDefault();
            // Include below line only if you have no other event listeners on the element, or its parents
            e.stopImmediatePropagation();
            return;
        }
    }

}

You block keys other than numbers only if number value already equals to 4 .仅当数字值已等于4时才阻止数字以外的键。 Try changing your blocking logic to:尝试将阻塞逻辑更改为:

if (String(value).length > 4 || !isNaN(Number(key)) || unwanted keyCodes) {
   e.preventDefault();
   return;

You can use a regex to test against the value of the input field and avoid messing with keyCodes.您可以使用正则表达式来测试输入字段的值并避免与 keyCodes 混淆。

if ( !/^[0-9]{0,4}$/.test(String(value)) ) {
    e.preventDefault();
    return;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 jQuery-如何允许数字键盘和数字键行输入; 以及防止输入特殊字符? - jQuery - How can I allow both numpad and number key row input; as well as prevent special characters from being entered? 如何使用javascript从字符串中拆分字符(所有语言环境)和数字? - How can I split the characters(all locales) and numbers from a string using javascript? 如何防止在输入字段中输入无效字符 - How to prevent invalid characters from being typed into input fields 使用正则表达式拆分 javascript 字符串以将数字与其他字符分开 - split javascript string using a regexp to separate numbers from other characters 如何防止通过表单输入提交字符 - How to prevent characters being submitted with form input 在 Javascript 中如何防止在 setTimeout 持续时间内调用其他函数? - In Javascript How do I prevent other functions from being invoked while under the setTimeout duration? 如何添加在JavaScript中输入的数字? - How do I add numbers that have been inputted in JavaScript? 如何防止将无效字符输入表单? - How do I prevent invalid characters from being entered into a form? Javascript / jQuery:如何防止活动输入字段被更改? - Javascript / jQuery: How to prevent active input field from being changed? 如何防止从html文件下载特定项目? ( <input type=“file”> ) - How can I prevent a specific item from being downloaded from my html file? (<input type=“file”>)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM