You can add [\b] to match and allow backspace.

Code:

var regex = new RegExp("^[a-zA-Z0-9\b]+$");

Demo: http://jsfiddle.net/M3bvN/

UPDATE

Instead of extend your regex you can check if the pressed key is in a list of allowed keys (arrows, home, del, canc) and if so skip the validation.

This not prevent the user to copy/paste not allowed characters. so perform the validation control in the blur event too (and always on server side).

Code:

var keyCode = event.keyCode || event.which
// Don't validate the input if below arrow, delete and backspace keys were pressed 
if (keyCode == 8 || (keyCode >= 35 && keyCode <= 40)) { // Left / Up / Right / Down Arrow, Backspace, Delete keys
    return;
}

Demo: http://jsfiddle.net/M3bvN/3/

Answer from Irvin Dominin on Stack Overflow
🌐
Medium
medium.com › luisbajana › allowing-only-alphanumeric-characters-89ff03d9171
Allowing only alphanumeric characters | by Luis Bajaña | luisbajana | Medium
September 18, 2017 - Sometimes you have to include some extreme validations over your text fields, the other day I had this requirement: “Allowing only alphanumeric characters and validate it when the user is typing”, you may say “there are tons of libraries for that purpose out there”, yes, but, what if you just want to validate one field? Include an entire library for that is too much… · [code language=”javascript”] $(‘body’).on(‘keypress’,’.js-only-alpha-numeric’, function (e){ var re = new RegExp(“^[a-zA-Z0–9]+$”, “g”); if(!re.test(String.fromCharCode(e.keyCode))) return false; }); [/code]
🌐
ASPSnippets
aspsnippets.com › Articles › 2686 › Perform-AlphaNumeric-validation-Alphabets-and-Numbers-using-OnKeyPress-in-JavaScript
Perform AlphaNumeric validation Alphabets and Numbers using OnKeyPress in JavaScript
January 29, 2019 - When User types in the TextBox, the text in the TextBox will be validated using OnKeyPress event handler in JavaScript and if the inputted character is not AlphaNumeric i.e. Alphabet or Number, the error message will be displayed next to the TextBox.
Top answer
1 of 2
6
  • onKeyValidate is an okay name, but a better name could be validateKeypress.

  • It seems very silly to store a RegExp as a string, and then construct it every time. Why not just declare var alpha = /[ A-Za-z]/?

  • keyChars appears to check against \x00, the null character, and \x08, the backspace character. Neither of these can ever be passed to onKeypress, so you can just take it out.

  • The standard way to get the character code is event.which || event.keyCode.

  • event is a global; I don't think you need to pass it in.

Here's a proposed rewrite:

var alpha = /[ A-Za-z]/;
var numeric = /[0-9]/; 
var alphanumeric = /[ A-Za-z0-9]/;

function validateKeypress(validChars) {
    var keyChar = String.fromCharCode(event.which || event.keyCode);
    return validChars.test(keyChar) ? keyChar : false;
}

The HTML will have to change to onkeypress="validateKeypress(alpha);".

2 of 2
1

The thing that I was able to pick out, and it's more of a nitpick type of things is that you should turn your last if statement around

if (!validChars.test(keychar) && !keyChars.test(keychar))   {
    return false
} else{
    return keychar;
}

should look like this

if (validChars.test(keychar) && keyChars.test(keychar)) {
    return keychar;
} else {
    return false;
}

Do your Positive first. most people like this better than all the negatives.

Side Note: for code golfing you just shaved 2 characters as well as made it more standard compliant if this nitpick can be considered a standard.

Short Version:

If you know Ternary operators and would like to use them instead of this simple if statement, @renatargh mentioned that you could make this super short

return validChars.test(keychar) && keyChars.test(keychar) ? keychar : false;

Also, var alphanumeric = "[ A-Za-z0-9]"; is never used (in this code block) and neither is var keyChars = /[\x00\x08]/;

you should just get rid of them

🌐
Code2night
code2night.com › Blog › MyBlog › Alphanumeric-validation-in-JavaScript
Alphanumeric validation in JavaScript | Code2night.com
August 14, 2022 - <form> <div class="form-group row"> <label for="inputPassword" class="col-sm-2 col-form-label">Enter Only Alphanumeric</label> <div class="col-sm-10"> <input type="text" class="form-control" id="inputAlphanumeric" placeholder="Enter Only Alphanumeric" value="" name="inputAlphanumeric" onkeypress="return onlyAlphanumerics(event)" /> </div> </div> </form> <script> function onlyAlphanumerics(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; } </script> So, this is how you can implement alphanumeric validation in JavaScript
🌐
Dot Net Techpoint
dotnettechpoint.com › 2020 › 07 › allow-only-alphanumeric-in-textbox.html
Allow only Alphanumeric in textbox onkeypress event - Dot Net Techpoint
July 25, 2020 - <script src="~/Scripts/jquery-1.10.2.js"></script> <label>Employee Name</label> <input type="text" id="txtEmployeeName" onkeypress="return ValidateUserName(event);" /><br /> <span id="lblErrorMessage" style="color:red"></span> Javascript code: I have created a ValidationUserName() for validate username which allow only alphanumeric.
🌐
Microsoft
social.msdn.microsoft.com › Forums › en-US › a2ce1089-b240-4e56-b8df-0326dfbfc349
How to validate alphanumric and space on keypress event | Microsoft Learn
November 12, 2013 - <div> <script type="text/javascript"> function IsAlphaNumeric(e) { // alert(e.keyCode); var keyCode = e.keyCode == 0 ?
🌐
Code2night
code2night.com › javascript › alphanumeric-validation-in-javascript
Alphanumeric validation in JavaScript | Code2night.com
August 14, 2022 - Alphanumeric validation restricts user input to letters and numbers, improving data quality. Use the onkeypress event and regular expressions to validate input in real-time. Always validate inputs on form submission to catch any bypasses.
🌐
ASP.NET Forums
forums.asp.net › t › 1949455.aspx
How to validate alphanumric and space on keypress event | The ASP.NET Forums
November 13, 2013 - ASP.NET Forums/General ASP.NET/jQuery for the ASP.NET Developer/How to validate alphanumric and space on keypress event · Last post Nov 13, 2013 02:30 AM by Happy Chen - MSFT ... .Net Consultant | MVP[2009-2013] | MCC[2012] Blog: ASPSnippets | Forum: ASPForums | Company: Excelasoft ... Happy Chen -... ... <div> <script type="text/javascript"> function IsAlphaNumeric(e) { // alert(e.keyCode); var keyCode = e.keyCode == 0 ?
Find elsewhere
🌐
Wordpress
dreamlandit.wordpress.com › 2013 › 02 › 11 › alphanumeric-number-validation-using-onkeypress-event
Alphanumeric & Number Validation using Onkeypress event | Website Design & Development Tips.
November 2, 2013 - <script language="javascript" type="text/javascript"> function isNumberKey(evt){ // Numbers only var charCode = (evt.which) ? evt.which : event.keyCode; if (charCode > 31 && (charCode < 48 || charCode > 57)) return false; return true; } function isAlphaNumeric(e){ // Alphanumeric only var k; document.all ?
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-validate-an-input-is-alphanumeric-or-not-using-javascript
How to Validate an Input is Alphanumeric or not using JavaScript? - GeeksforGeeks
July 12, 2025 - let input = "validate1234@"; // Function to validate alphanumeric input function validateFunc(input) { let val = input.trim(); let RegEx = /^[a-z0-9]+$/i; let Valid = RegEx.test(val); if (Valid) { console.log("The input is valid and alphanumeric."); ...
🌐
Devcurry
devcurry.com › 2009 › 10 › allow-only-alphanumeric-characters-in.html
Allow Only Alphanumeric Characters in a TextBox using jQuery
Since we are capturing the keyup event, we are also preventing copying and pasting of non-alphanumeric characters. I have observed people using the keypress event to handle this requirement, but remember that in IE, keypress does not behave as expected for non-character keys. As Yehuda Katz says – “My mantra has always been: keydown/keyup if you want to know the key that was pressed; keypress if you want to know what text was detected” · Note: Javascript can be disabled, so always validate the user input on server side
🌐
C# Corner
c-sharpcorner.com › code › 1681 › only-alphanumeric-javascript-no-special-character.aspx
Only Alphanumeric JavaScript No Special Character
September 23, 2015 - <asp:TextBox ID="GroupCode" runat="server" MaxLength="50" onkeypress="return noAlphabets(event)" ></asp:TextBox>
🌐
Stack Overflow
stackoverflow.com › questions › 46976008 › keypress-validation-which-should-not-allow-alphabet-only-but-all-other-key-shoul
javascript - Keypress validation which should not allow alphabet only but all other key should work - Stack Overflow
$('#value').bind('keypress', function (e) { if ($('#value').val().length == 0) { if (e.which == 32) { //space bar e.preventDefault(); } var valid = (e.which >= 48 && e.which <= 57) || (e.which >= 65 && e.which <= 90) || (e.which >= 97 && e.which <= 122); if (!valid) { e.preventDefault(); } } else { var valid = (e.which >= 48 && e.which <= 57) || (e.which >= 65 && e.which <= 90) || (e.which >= 97 && e.which <= 122 || e.which == 32 || e.which == 95 || e.which == 8); if (!valid) { e.preventDefault(); } } });
🌐
.Training
itdeveloperzone.com › 2012 › 03 › validate-alphanumeric-javascript.html
Validate Alphanumeric Javascript
These intensive programs emerged to address the gap between traditional computer science education and industry demand for practical coding skills. Modern developer training bootcamps focus on in-demand technologies like JavaScript, Python, React, Node.js, cloud platforms, and agile methodologies through hands-on project work that simulates real development environments.
🌐
Medium
shivapendem.medium.com › input-only-numbers-or-alphanumeric-html-input-50bea70bc6f
Input only numbers or alphanumeric html input | by Pendem Shiva Shankar | Medium
May 31, 2021 - <input type="text" id="text1" onkeypress="return IsAlphaNumeric(event);" ondrop="return false;" onpaste="return false;" /> ... <script type="text/javascript"> var specialKeys = new Array(); specialKeys.push(8); //Backspace specialKeys.push(9); ...