[英]How to restrict user from entering number in to an input field with type as text?
How to disable the user from entering a number in to input field.如何禁止用户在输入字段中输入数字。 When we use type as number we are restricted from entering text in to the input.The same way how to achieve the vice versa.当我们使用类型作为数字时,我们被限制在输入中输入文本。同样的方式如何实现反之亦然。 Someone help i need this to complete my assignment.有人帮助我需要这个来完成我的任务。
<input type="text" name="name" />
You can listen to keydown
, and if the key pressed is a number, just call event.preventDefault()
on the keyboard event.您可以收听keydown
,如果按下的键是数字,只需在键盘事件上调用event.preventDefault()
即可。
const input = document.querySelector('input'); input.addEventListener('keydown', function(event){ if((/\d/g).test(event.key)) event.preventDefault(); })
<input type="text" />
You can add an input
event listener to the input which gets the input's value, replaces every numeric character (with String.replace
), then assigns the result back to the input's value:您可以将input
事件侦听器添加到获取输入值的输入,替换每个数字字符(使用String.replace
),然后将结果分配回输入值:
const input = document.querySelector('input'); input.addEventListener('input', function(){ this.value = this.value.replace(/[^\D]/g,'') })
<input type="text" name="name" />
You can use 1 line function to prevent any number in the input
with help of regular expression您可以使用 1 行 function 在正则表达式的帮助下防止input
中的任何数字
But it is not recommended to use inline function, here is provided only to tell about a different approach但是不推荐使用inline function,这里提供只是说一下不同的做法
See here to know more about regular expression 请参阅此处以了解有关正则表达式的更多信息
<input type="text" name="name" oninput=" this.value = this.value.replace(/[0-9]/g,'')" />
Try to use pattern
with regex:尝试将pattern
与正则表达式一起使用:
<input type="text" name="name" pattern="\D" />
\D
will reject all digits \D
将拒绝所有数字
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.