Detect numbers or letters with jQuery/JavaScript?

If you want to check a range of letters you can use greater than and less than:

if (event.keyCode >= 48 && event.keyCode <= 57) {
  alert('input was 0-9');
}
if (event.keyCode >= 65 && event.keyCode <= 90) {
  alert('input was a-z');
}

For a more dynamic check, use a regular expression:

const input = String.fromCharCode(event.keyCode);

if (/[a-zA-Z0-9-_ ]/.test(input)) {
  alert('input was a letter, number, hyphen, underscore or space');
}

See the MDC documentation for the keyCode property, which explains the difference between that and the which property and which events they apply to.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)