Home > Blockchain >  How to restrict user from entering number in to an input field with type as text?
How to restrict user from entering number in to an input field with type as text?

Time:10-03

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" />

CodePudding user response:

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" />

CodePudding user response:

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" />

CodePudding user response:

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,'')" />

CodePudding user response:

Try to use pattern with regex:

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

\D will reject all digits

  • Related