0

In textbox, I only want to allow numbers, backspace, left and right arrow keys and shift + arrow keys(for selection) to get typed and block typing of alphabets and special characters.

Tried using following code:

var key = e.which || this.value.substr(-1).charCodeAt(0);
key = String.fromCharCode(key);
var regex = /^[0-9\b]+$/;

With Regex:

if(!regex.test(key) && !(e.shiftKey && (e.keyCode == 37 || e.keyCode == 39)) && e.keyCode!=37 && e.keyCode!=39)
return false;

Above code blocks typing of alphabets but allows special characters.

Without Regex:

if((e.shiftKey && e.keyCode > 48 && e.keyCode < 57) || (e.keyCode <= 48 && e.keyCode >= 57) || (e.keyCode <=96 && e.keyCode >=105))
return false;

But in above code user can see characters getting typed and removed.

I want to block typing of alphabets and special characters. Can anyone correct my code ?

Nikunj V
  • 271
  • 4
  • 18
  • Why not [html pattern](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/pattern)? – skobaljic Nov 11 '21 at 14:25
  • @skobaljic Because I am masking characters to X while typing – Nikunj V Nov 11 '21 at 14:27
  • I think you need only number value to be allowed as input, then check: https://stackoverflow.com/questions/469357/html-text-input-allow-only-numeric-input/469362#469362 , also check: https://stackoverflow.com/questions/995183/how-to-allow-only-numeric-0-9-in-html-inputbox-using-jquery – D Coder Nov 11 '21 at 14:30

0 Answers0