简体   繁体   中英

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.

 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:

 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

But it is not recommended to use inline function, here is provided only to tell about a different approach

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:

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

\D will reject all digits

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM