过滤输入文本以仅输入数字,甚至不输入小数 [英] Filter input text to enter only number and not even decimal

查看:25
本文介绍了过滤输入文本以仅输入数字,甚至不输入小数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是让用户只输入 [0-9] 中的数字,甚至不允许使用小数

怎么做?

代码

</b-输入>

来自 buefy https://buefy.github.io/documentation/input/

解决方案

来自 Beufy doc,我知道 本质上是原生 字段的扩展,因此它接受原生输入将接受的属性.

截至目前,无法使用 pattern="\d+" 等纯 HTML 属性完全过滤掉特定字符.

您可以做的是使用keydown"事件侦听器使用原生 event.preventDefault() 由各自的 .当然,我们可以使用原生的 来提供帮助.

const app = new Vue({el: '#app',方法: {过滤键(e){const key = e.key;//如果是 '.'关键,停下来如果(键 === '.')返回 e.preventDefault();//可选的//如果是 'e' 键,则停止如果(键 === 'e')返回 e.preventDefault();},//这也可以防止复制+粘贴无效字符过滤器输入(e){e.target.value = e.target.value.replace(/[^0-9]+/g, '');}}});

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script><div id="应用程序"><输入类型=数字"步骤=1"分钟=0"@keydown="过滤键"//或者@input="过滤器输入">

My goal is for the user to only enter number from [0-9] not even decimal is allowed

How to do that?

The code

<b-input expanded
    type="number"
    v-model="amount"
    @input="updateValue()"
    placeholder="{{ amount }}">
</b-input>

The <b-input> is from buefy https://buefy.github.io/documentation/input/

解决方案

From the Beufy doc, I get that <b-input> is essentially an extension of native <input> field so it accepts attribute that the native input would accept.

As of now, it is not possible to completely filter out specific characters using pure HTML attributes like pattern="\d+".

What you can do is to use a "keydown" event listener to filter out these characters using native event.preventDefault() by respective keys. Of course, we could use the native <input type="number"> to help in general.

const app = new Vue({
  el: '#app',
  methods: {
    filterKey(e){
      const key = e.key;

      // If is '.' key, stop it
      if (key === '.')
        return e.preventDefault();
      
      // OPTIONAL
      // If is 'e' key, stop it
      if (key === 'e')
        return e.preventDefault();
    },
    
    // This can also prevent copy + paste invalid character
    filterInput(e){
      e.target.value = e.target.value.replace(/[^0-9]+/g, '');
    }
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <input
    type="number"
    step="1"
    min="0"
    
    @keydown="filterKey"
    // OR 
    @input="filterInput"
  >
</div>

这篇关于过滤输入文本以仅输入数字,甚至不输入小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆