'Detect numbers or letters with jQuery/JavaScript?

I want to use an if-statement to run code only if the user types in a letter or a number.

I could use

if (event.keyCode == 48 || event.keyCode == 49 || event.keyCode == 50 || ...) {
  // run code
}

Is there an easier way to do this? Maybe some keycodes don't work in all web browsers?



Solution 1:[1]

Use event.key and modern JS!

No number codes anymore. You can check key directly.

const key = event.key.toLowerCase();

if (key.length !== 1) {
  return;
}

const isLetter = (key >= 'a' && key <= 'z');
const isNumber = (key >= '0' && key <= '9');

if (isLetter || isNumber) {
  // Do something
}

You could also use a simple regex. ^$ ensures 1 char, i ignores case

/^[a-z0-9]$/i.test(event.key)

or individually:

const isLetter = /^[a-z]$/i.test(event.key)
const isNumber = /^[0-9]$/i.test(event.key)

Solution 2:[2]

First, if you're doing this, make sure it's in the keypress event, which is the only event for which you can reliably obtain information about the character the user has typed. Then I'd use the approach Andy E suggested:

document.onkeypress = function(evt) {
   evt = evt || window.event;
   var charCode = evt.which || evt.keyCode;
   var charStr = String.fromCharCode(charCode);
   if (/[a-z0-9]/i.test(charStr)) {
       alert("Letter or number typed");
   }
};

If you want to check for backspace, I'd use the keydown event instead and check for a keyCode of 8 because several browsers (including Chrome) do not fire a keypress event for the backspace key.

Solution 3:[3]

if (event.keyCode >= 48 && event.keyCode <= 90) {
  // the key pressed was alphanumeric
}

Solution 4:[4]

As @Gibolt said, you should use event.key.

Because charCode, keyCode and which are being deprecated.

Solution 5:[5]

For numeric values:

function validNumeric() {
  var charCode = event.which ? event.which : event.keyCode;
  var isNumber = charCode >= 48 && charCode <= 57;

  if (isNumber) {
    return true;
  } else {
    return false;
  }
}

Here, 48 to 57 is the range of numeric values.

For alphabetic values:

function validAlphabetic() {
  var charCode = event.which ? event.which : event.keyCode;
  var isCapitalAlphabet = charCode >= 65 && charCode <= 90;
  var isSmallAlphabet = charCode >= 97 && charCode <= 122;

  if (isCapitalAlphabet || isSmallAlphabet) {
    return true;
  } else {
    return false;
  }
}

Here, 65 to 90 is the range for capital alphabets (A-Z), and

97 to 122 is the range for small alphabets (a-z).

Solution 6:[6]

To detect letters & numbers when using <input> or <textarea> you can use input event.

This event fires when <input> or <textarea> value changes so there is no need to worry about keys like Alt, Shift, arrows etc. Even more - if you use mouse to cut part of the text the event fires as well.

var element = document.getElementById('search');

element.addEventListener('input',function(e){

  console.log(element.value);

});
<input id="search" type="text" placeholder="Search" autocomplete="off">

Solution 7:[7]

Simply you can add your Html forms in the input field like this:

...onkeypress ="return /[a-z .@ 0-9]/i.test(event.key)" required accesskey="4"

You don't need any function. This Validation works only with the email field. Don't use naming or number. To use number, remove email regular expression like this:

...onkeypress ="return /[a-z ]/i.test(event.key)" required accesskey="4"

For number only:

...onkeypress ="return /[0-9]/i.test(event.key)" required accesskey="4"

Don't forget, to add for each input fields their own value.

<div class="form-group">
   <input type="Email" class="form-control " id="EMAILADDRESS" name="EMAILADDRESS" placeholder="Email Address"   autocomplete="false" onkeypress ="return /[a-z .@ 0-9]/i.test(event.key)" required accesskey="4"/>  
</div>

Solution 8:[8]

$('#phone').on('keydown', function(e) {
  let key = e.charCode || e.keyCode || 0;

  // 32 = space - border of visible and non visible characters - allows us to backspace and use arrows etc
  // 127 - delete
  if (key > 32 && (key < 48 || key > 58) && key !== 127) {
    e.preventDefault();
    return false;
  }
});

modified answer of @user4584103, allows us to remove characters, and navigate in input box and filter out every not number character

Solution 9:[9]

You can also use charCode with onKeyPress event:

if (event.charCode > 57 || event.charCode < 48) {
  itsNotANumber();
} else {
  itsANumber();
}

Solution 10:[10]

number validation, works fine for me

$(document).ready(function () {
  $('.TxtPhone').keypress(function (e) {
    var key = e.charCode || e.keyCode || 0;

    // only numbers
    if (key < 48 || key > 58) {
      return false;
    }
  });
});

Solution 11:[11]

Accept numbers or letters with JavaScript by Dynamic Process using regular expression.

Add onkeypress event for specific control

onkeypress="javascript:return isNumber(event)"

function numOnly(evt) {
  evt = evt || window.event;
  var charCode = evt.which || evt.keyCode;
  var charStr = String.fromCharCode(charCode);

  if (/[0-9]/i.test(charStr)) {
    return true;
  } else {
    return false;
  }
}

function Alphanum(evt) {
  evt = evt || window.event;
  var charCode = evt.which || evt.keyCode;
  var charStr = String.fromCharCode(charCode);

  if (/[a-z0-9]/i.test(charStr)) {
    return true;
  } else {
    return false;
  }
}

Solution 12:[12]

Use $.isNumeric(value); return type is boolean

$(document).ready(function () {
  return $.isNumeric(event.keyCode);
});