Detect numbers or letters with jQuery/JavaScript?
Asked Answered
C

14

82

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?

Chlordane answered 13/2, 2010 at 9:26 Comment(1)
Just adding in a comment that keycode and which are deprecated and its suggested to use KeyboardEvent.keyVerdin
D
153

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.

Discharge answered 13/2, 2010 at 9:34 Comment(14)
how do i check a 'backspace' with the dynamic check?Chlordane
Note that this has to be done in the keypress event rather than the keydown event.Eadwina
Be aware that oddly, String.fromCharCode can turn non-typeable keys into characters. For example when I press the left command key on my mac I get "[" and for the right I get "]".Chemurgy
@chaiguy: yes, as @TimDown said, you're better off using it in conjunction with the keypress event, which doesn't fire (in most browsers) for most non-input keys.Discharge
Don't forget the numeric keypad: (event.keyCode >= 96 && event.keyCode <= 105) =PRitualism
@ThomasC.G.deVilhena: that's not necessary when you're capturing the onkeypress event :-P (Tim kindly pointed that out in comment #2)Discharge
@AndyE MDC Docs state that keyCode property is deprecated & should not be used.. what would be the work around for this?Lime
@techie_28: keyCode and which are both deprecated but it won't be going away as it's required for web compatibility. event.key is the future but has poor support at the minute. I generally use key these days with a fallback of mapping keyCode to key values, but you can live without fear of keyCode going away for a long time to come.Discharge
@AndyE thanks.. the MDC Doc is warning strongly against its use so I was bit concerned.Lime
@AndyE I think (event.keyCode >= 96 && event.keyCode <= 105) should also be included for the NumLock keys?Lime
@techie_28: that depends entirely on the event. I'd recommend handling keypress only if you can get away with it, then numpad keys have the same keyCode.Discharge
F5 has charCode 116, and String.fromCharCode(116) gives 't'. Happy programming XDUndergarment
This answer is deprecated nowdays. See @Warwick answerBedabble
Not sure why it is deprecated if it is the only version that works with Internet Explorer.Fibrinolysis
W
46

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)
Warwick answered 18/2, 2018 at 19:48 Comment(5)
This is wrong! (key >= "a" && key <= "z") will return true for almost anything (e.g. when key = Insert). Same with /[a-z]/i.test('Insert')Lohse
There is a length !== 1 check you missed. Fixed the regexWarwick
Is it safe to assume that event.key.lenght === 1 covers every letter, number, space and symbol? I've been testing key.length and found that control keys have length > 1. Still, not sure if this is a good aproachBedabble
I can't guarantee that this works for anything beyond numbers and letters, which was the original question. Some international keyboards potentially could have >1 length keys. For Control, Escape, etc. directly check the value like "Enter" instead of lengthWarwick
@alwin-kesler event.key.lengthCliffcliffes
E
27

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.

Eadwina answered 13/2, 2010 at 13:21 Comment(5)
This is a much better answer as this is probably the behavior that people are looking for.Alkaline
"If you want to check for backspace, I'd use if (charCode == 8) {...}" --- I've tried this, onkeypress doesn't fire for backspacePlexus
@TKoL: Interesting. It does fire in Firefox but not Chrome. That's changed since 2010.Eadwina
@TKoL: Or has it? I'm not sure now after a bit of googling. I'd normally check something like that before asserting it though.Eadwina
'delete' doesn't fire for keypress for me on multiple platforms, including jsfiddle on chrome and Windows Store html appsPlexus
A
7
if (event.keyCode >= 48 && event.keyCode <= 90) {
  // the key pressed was alphanumeric
}
Alcorn answered 13/2, 2010 at 9:33 Comment(0)
G
3

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).

Gaily answered 6/5, 2019 at 20:24 Comment(0)
L
2

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

Because charCode, keyCode and which are being deprecated.

Lazos answered 18/6, 2018 at 16:53 Comment(0)
G
1

$('#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

Glossology answered 7/11, 2017 at 23:47 Comment(0)
S
1

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">
Spiller answered 20/1, 2021 at 5:29 Comment(0)
R
1

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>
Rosaline answered 11/12, 2021 at 17:30 Comment(0)
B
0

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;
    }
  });
});
Bushwa answered 26/4, 2016 at 10:59 Comment(0)
M
0

You can also use charCode with onKeyPress event:

if (event.charCode > 57 || event.charCode < 48) {
  itsNotANumber();
} else {
  itsANumber();
}
Mountie answered 10/3, 2017 at 12:0 Comment(0)
W
0

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

$(document).ready(function () {
  return $.isNumeric(event.keyCode);
});
Whereon answered 18/7, 2017 at 8:48 Comment(0)
B
0

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;
  }
}
Bibcock answered 12/10, 2017 at 7:8 Comment(0)
D
0

A very simple, but useful method to try (i needed on a keyup event, letters only), use console.log() to check, typeOfKey is a string so you can compare. typeOfKey is either (Digit or Key)

 let typeOfKey = e.code.slice(0,-1) 
  if(typeOfKey === 'Key'){
  console.log(typeOfKey)  
}
Digiovanni answered 19/11, 2022 at 11:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.