如何限制用户在以文本形式输入类型的输入字段中输入数字



如何禁止用户在输入字段中输入数字。当我们使用类型作为数字时,我们被限制在输入中输入文本。同样的方式如何实现反之亦然。有人帮我完成任务。

<input type="text" name="name" />

您可以收听keydown,如果按下的键是数字,只需在键盘事件上调用event.preventDefault()即可。

const input = document.querySelector('input');
input.addEventListener('keydown', function(event){
if((/d/g).test(event.key)) event.preventDefault();
})
<input type="text" />

您可以向输入添加一个input事件侦听器,该侦听器获取输入的值,用String.replace替换每个数字字符,然后将结果分配回输入的值:

const input = document.querySelector('input');
input.addEventListener('input', function(){
this.value = this.value.replace(/[^D]/g,'')
})
<input type="text" name="name" />

借助正则表达式,您可以使用1行函数来防止input中的任何数字

但不建议使用内联函数,这里只提供了一种不同的方法

请参阅此处了解有关正则表达式的更多信息

<input type="text" name="name" oninput=" this.value = this.value.replace(/[0-9]/g,'')" />

尝试将pattern与regex:一起使用

<input type="text" name="name" pattern="D" />

D将拒绝所有数字

最新更新