18

Live Demo: http://jsfiddle.net/thisizmonster/DveuB/

How can I change this so that the input only allows the characters A-Z, a-z, 0-9 while typing, without using a regular expression?

6
  • The method you want is called keypress, not keyPress. Aug 22, 2011 at 7:13
  • 1
    Why without regEx? This would be really easy with regEx!
    – Sam Martin
    Aug 22, 2011 at 7:14
  • You'd still need add a special case for control chars. Aug 22, 2011 at 7:16
  • Because I don't know regEx! Can you do it for me?
    – Gereltod
    Aug 22, 2011 at 7:16
  • 2
    "while typing" So mouse copy&paste or other types of non-keyboard input are okay?
    – pyvi
    Aug 22, 2011 at 8:52

7 Answers 7

47

Assuming you also want to accept spaces:

$("#user").keypress(function(event){
    var ew = event.which;
    if(ew == 32)
        return true;
    if(48 <= ew && ew <= 57)
        return true;
    if(65 <= ew && ew <= 90)
        return true;
    if(97 <= ew && ew <= 122)
        return true;
    return false;
});

If you don't want to accept spaces then remove the if(ew == 32) return true;

JSFiddle

5
  • I just entered a é (alt-e-e) in your text box on OSX, it does stop µ though. Neither Safari nor Firefox trigger keypress events for composed characters on OSX. Aug 22, 2011 at 7:25
  • @Gerelt See my updated post for a new link to prevent what 'mu is too short' is talking about!
    – 321X
    Aug 22, 2011 at 7:32
  • the bad thing is that the user is able to paste a mal-formatted string
    – manix
    Dec 3, 2012 at 5:08
  • 1
    @Mir for Backspace add if (ew == 8) return true; Jan 28, 2017 at 10:22
  • 1
    Could someone also give an idea on how to avoid or restrict characters like ý, Ý â, ê, î, ô, û etc from typing or pasting into the input field?
    – Vineet
    Feb 5, 2017 at 13:34
10

<input type="text" id="firstName"  onkeypress="return (event.charCode >= 65 && event.charCode <= 90) || (event.charCode >= 97 && event.charCode <= 122) || (event.charCode >= 48 && event.charCode <= 57)" />

The ASCII Character Set : https://www.w3schools.com/charsets/ref_html_ascii.asp

2
  • 1
    Note that this wouldn't stop the user from copying & pasting unwanted characters into the input field.
    – Pang
    May 24, 2017 at 3:12
  • you can change "onkeypress" to "onblur". Jul 3, 2017 at 1:43
7

All other answers are fine but don't prevent copy and paste non-English characters.

‌Bellow code works for both (key press and copy-paste):

<input type="text" name="text" oninput="this.value=this.value.replace(/[^A-Za-z\s]/g,'');">
2
  • I wish I understood regex, honestly I wish regex went away replaced with something easier to create. Oh great RegEx master, how do I add 0-9 to this? May 13, 2022 at 11:28
  • @EricWeintraub, you can use this /[^0-9A-Za-z\s]/g May 13, 2022 at 15:04
2

You can do something like this: http://jsfiddle.net/DveuB/1/

Then it's only 0-9, a-z and A-Z

$(function(){
    $("#user").keypress(function(event){
        if ((event.charCode >= 48 && event.charCode <= 57) || // 0-9
            (event.charCode >= 65 && event.charCode <= 90) || // A-Z
            (event.charCode >= 97 && event.charCode <= 122))  // a-z
            alert("0-9, a-z or A-Z");
    });
});

Update: http://jsfiddle.net/DveuB/4/
To prevent what @mu is talking about:

$("#user").keyup(function(event){
    if (event.altKey == false && event.ctrlKey == false)
        if ((event.keyCode >= 48 && event.keyCode <= 57 && event.shiftKey== false) ||
            (event.keyCode >= 65 && event.keyCode <= 90) ||
            (event.keyCode >= 97 && event.keyCode <= 122))
            alert("0-9, a-z or A-Z");
});
3
  • I can get a composed character (such as é which is built from alt-e-e) past that on OSX in both Safari and Firefox, those characters don't seem to trigger keypress events. Aug 22, 2011 at 7:23
  • if(event.keyCode == 8) return true;
    – peiman F.
    Aug 23, 2017 at 18:21
  • answer missed out. you should test repeat "point" (.) you can enter more than one. Jul 9, 2018 at 12:44
2
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function () {

  $('.clsAlphaNoOnly').keypress(function (e) {  // Accept only alpha numerics, no special characters 
        var regex = new RegExp("^[a-zA-Z0-9 ]+$");
        var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
        if (regex.test(str)) {
            return true;
        }

        e.preventDefault();
        return false;
    }); 
})
</script>

<body>

<input class='clsAlphaNoOnly' type='text'>
</body>
</html>
1

I'm using this function.

By modifying RegExp you can get rid of any characters you don't like personally.

$(function(){
    $("#user").bind('keypress',function(e){
        var regex = new RegExp("^[a-zA-Z0-9 ]+$");
        var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
        if (regex.test(str)) return true;
        e.preventDefault();
        return false;
    });
});
0

Think you have to write some if statements or something like that, that takes the keycode and validates it against some numbers that represent other keycodes:

for example: if(keycode < 80) return false;

3
  • 1
    This code will prevent you from using backspace. You need to handle control chars and always allow them. Aug 22, 2011 at 7:16
  • This was just for the example. Of course you need to figure out which codes you want to allow (like backspace, arrows, etc.) and which codes you want to ignore. Aug 22, 2011 at 7:19
  • This has the same problem as 321X's on OSX. Aug 22, 2011 at 7:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.