There are a couple of libraries that you could use. If you want to stick to pure JavaScript without any jQuery, then your best option would probably be Validate JS.

There are a ton of jQuery options if you are willing to work with jQuery - these are usually more feature packed and nicer to look at too. You could also use the Validator built into the Foundation Framework - it's called Abide but it uses jQuery.

Hope this helps.

Answer from Nischaal Cooray on Stack Overflow
🌐
Fromanegg
fromanegg.com › post › 2012 › 12 › 29 › form-validation-with-keydown-keypress-and-keyup
Form validation with keydown, keypress, and keyup · From An Egg
December 29, 2012 - var input = document.getElementsByName('currency-field')[0], currencyRegex = /^[0-9]{0,5}(\.[0-9]{0,2})?$/; function handleKeypress(e) { // Get the string value of the charCode. var char = String.fromCharCode(e.charCode), target = e.target, inputVal = target.value, // Construct what the value will be if the event is not prevented. value = inputVal.substr(0, target.selectionStart) + char + inputVal.substr(target.selectionEnd); // Test to make sure the user is inputting only valid characters // and that the resulting input is valid. if (!char.match(/[0-9.]/) || !value.match(currencyRegex)) { tog
Discussions

JavaScript onKeypress validation - Code Review Stack Exchange
Stack Exchange network consists of 183 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers · Ask questions, find answers and collaborate at work with Stack Overflow for Teams More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
December 8, 2014
javascript - Input validation in the keydown event - Stack Overflow
I'm attempting to do info validation against user text input in the process of keydown event. The reason that I am trying to validate in the keydown event is because I do not want to display the More on stackoverflow.com
🌐 stackoverflow.com
html - How do I detect keypresses in Javascript? - Stack Overflow
After looking around on the internet, I've seen a lot of suggestions (use window.onkeypress, use jQuery, etc.) but for almost every option there's a counterargument. How can I detect a keypress in More on stackoverflow.com
🌐 stackoverflow.com
javascript - Number validate at keypress - Stack Overflow
I validate the phone number using below code its working fine but i allow char at first time while user entering the values. how i can solve it. . . . $('.Number').keypress(function () { $('.N... More on stackoverflow.com
🌐 stackoverflow.com
May 22, 2017
🌐
JavaScript Kit
javascriptkit.com › javatutors › javascriptkey3.shtml
Form validation using the keyboard events
Click here for comprehensive JavaScript tutorials, and over 400+ free scripts!
🌐
W3Schools
w3schools.com › jsref › event_onkeypress.asp
onkeypress Event
To detect if the user presses a key, always use the onkeydown event. It works for all keys. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com · If you want to ...
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

Top answer
1 of 4
15

If you're checking a printable key, which is exactly what you seem to be doing, you should use the keypress event instead, since that's the only place you're going to be able to get reliable information about the character the keypress represents. You can't detect numeric keypresses reliably in the keydown event. Also, it's a bad idea to suppress arrow keys and delete/backspace keys. What do you gain from doing that?

There's also some errors: in Firefox, you'll need to get the Event object from the parameter passed into the event handler function, and if you're using a DOM0 event handler function rather than addEventListener() or attachEvent(), you should use return false; to suppress default behaviour. Here's my recommended code:

var input = document.getElementById("your_input_id");

input.onkeypress = function(evt) {
    evt = evt || window.event;
    var charCode = evt.which || evt.keyCode;
    var charStr = String.fromCharCode(charCode);
    if (/\d/.test(charStr)) {
        return false;
    }
};
2 of 4
1

I don't think you need the preventDefault part. If you want to catch keys (by event.keyCode, or combinations using for example event.ctrlKey + event.keyCode), you check if the keyCode is allowed. If it is, simply return true, otherwise return false. If you return false, the key input will not be written to the input field, otherwise it will.

I can't think of better ways to then using keyCode. You can use String.fromCharCode([keyCode]) if you want to check for specific character values, but it keeps boiling down to some loop to check the keyCodes you want to validate. May be a switch ... case could offer a bit more readability.

Here's a piece of code from a keydown event handler I use (just for demonstration, it doesn't actually do anything):

function handleKey(e, thisFld) {
        thisFld = (thisFld || this);
              e = e || event;
    if (!e) {
      return true;
    }

    var isCtrl = e.ctrlKey,
        isShift = e.shiftKey,
        isAlt = e.altKey,
        kc = e.keyCode || e.which,
        codes = [27, 38, 40],
        keys = {
                 escape: 27,
                 up: 38,
                 down: 40,
                 ins: 45,
                 del: 46,
                 one: 49
                };

    if (isCtrl && kc === keys.del) { ... }
    if (isAlt && kc === keys.ins) { ... }
        //etc
    return true;
}
🌐
ASPSnippets
aspsnippets.com › Articles › Perform-Email-validation-using-OnKeyPress-in-JavaScript.aspx
Perform Email validation using OnKeyPress in JavaScript
January 28, 2019 - ValidateEmail JavaScript function. <input type="text" id="txtEmail" onkeyup="ValidateEmail();" /> ... OnKeyUp event handler in JavaScript and if the Email Address is invalid, the error message will be displayed next to the TextBox.
🌐
C# Corner
c-sharpcorner.com › blogs › numeric-keypress-validation-in-textbox-using-javascript1
Numeric KeyPress Validation in TextBox using JavaScript
May 19, 2020 - ... <%@ Page Language="C#" ...idation.Home" %> ... Numeric Value: <input type="text" id="text1" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;" />...
Find elsewhere
🌐
Agyan Adda
agyanadda.com › question › how-to-validate-name-using-regex-onkeypress-in-javascript
How to validate name using regex onkeypress in JavaScript - agyanadda
<!DOCTYPE html> <html> <head> <title>Alpha Numeric validation Example</title> </head> <body> <label>Enter only Alpha numeric Character</label><br><br> <input type="text" id="txtName" onkeypress="return ValidateAlphanumeric(event);" /> <span id="lblError" style="color: red"></span> <script type="text/javascript"> function ValidateAlphanumeric(e) { var keyCode = e.keyCode || e.which; var lblError = document.getElementById("lblError"); lblError.innerHTML = ""; //Regex for Valid Characters i.e.
Top answer
1 of 6
138

With plain Javascript, the simplest is:

document.onkeypress = function (e) {
    e = e || window.event;
    // use e.keyCode
};

But with this, you can only bind one handler for the event.

In addition, you could use the following to be able to potentially bind multiple handlers to the same event:

addEvent(document, "keypress", function (e) {
    e = e || window.event;
    // use e.keyCode
});

function addEvent(element, eventName, callback) {
    if (element.addEventListener) {
        element.addEventListener(eventName, callback, false);
    } else if (element.attachEvent) {
        element.attachEvent("on" + eventName, callback);
    } else {
        element["on" + eventName] = callback;
    }
}

In either case, keyCode isn't consistent across browsers, so there's more to check for and figure out. Notice the e = e || window.event - that's a normal problem with Internet Explorer, putting the event in window.event instead of passing it to the callback.

References:

  • https://developer.mozilla.org/en-US/docs/DOM/Mozilla_event_reference/keypress
  • https://developer.mozilla.org/en-US/docs/DOM/EventTarget.addEventListener

With jQuery:

$(document).on("keypress", function (e) {
    // use e.which
});

Reference:

  • http://api.jquery.com/on/

Other than jQuery being a "large" library, jQuery really helps with inconsistencies between browsers, especially with window events...and that can't be denied. Hopefully it's obvious that the jQuery code I provided for your example is much more elegant and shorter, yet accomplishes what you want in a consistent way. You should be able to trust that e (the event) and e.which (the key code, for knowing which key was pressed) are accurate. In plain Javascript, it's a little harder to know unless you do everything that the jQuery library internally does.

Note there is a keydown event, that is different than keypress. You can learn more about them here: onKeyPress Vs. onKeyUp and onKeyDown

As for suggesting what to use, I would definitely suggest using jQuery if you're up for learning the framework. At the same time, I would say that you should learn Javascript's syntax, methods, features, and how to interact with the DOM. Once you understand how it works and what's happening, you should be more comfortable working with jQuery. To me, jQuery makes things more consistent and is more concise. In the end, it's Javascript, and wraps the language.

Another example of jQuery being very useful is with AJAX. Browsers are inconsistent with how AJAX requests are handled, so jQuery abstracts that so you don't have to worry.

Here's something that might help decide:

  • http://www.jscripters.com/jquery-disadvantages-and-advantages/
2 of 6
60

NOTE: JS's keypress is deprecated:

https://developer.mozilla.org/en-US/docs/Web/API/Element/keypress_event

The jQuery solutions in this answer may still be relevant.


KEYPRESS (enter key)
Click inside the snippet and press Enter key.

Vanilla

document.addEventListener("keypress", function(event) {
  if (event.keyCode == 13) {
    alert('hi.');
  }
});

Vanilla shorthand (Arrow Function, ES6)

this.addEventListener('keypress', event => {
  if (event.keyCode == 13) {
    alert('hi.')
  }
})

jQuery

$(this).on('keypress', function(event) {
  if (event.keyCode == 13) {
    alert('hi.')
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

jQuery classic

$(this).keypress(function(event) {
  if (event.keyCode == 13) {
    alert('hi.')
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

jQuery shorthand (Arrow Function, ES6)

$(this).keypress((e) => {
  if (e.keyCode == 13)
    alert('hi.')
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Even shorter (ES6, ECMAScript 2021)

$(this).keypress(e=>
  e.which==13&&alert``
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Due to some requests, here is an explanation:

I rewrote this answer as things have become deprecated over time so I updated it. Just for info, it is not about "keydown", it's about "keypress". So some non-character keys like "Esc" aren't supposed to work like that but I'll explain.

I used this to focus on the window scope inside the results when document is ready and for the sake of brevity but it's not necessary.

Deprecated:
The .which and .keyCode methods are actually considered deprecated so I would recommend .code but I personally still use keyCode as the performance is much faster and only that counts for me. The jQuery classic version .keypress() is not officially deprecated as some people say but they are no more preferred like .on('keypress') as it has a lot more functionality(live state, multiple handlers, etc.). The 'keypress' event in the Vanilla version is also deprecated. People should prefer beforeinput or keydown, keyup today.

Performance:
The faster the better. This is why I prefer .keyCode even if it's considered deprecated(in most cases). It's all up to you though (Commited 2020).

Performance Test

🌐
TutorialsPoint
tutorialspoint.com › article › What-is-onkeypress-event-in-JavaScript
What is onkeypress event in JavaScript?
<html> <head> <script> function ... code: " + keyCode); // Example: Only allow numbers if (keyCode < 48 || keyCode > 57) { event.preventDefault(); alert("Only numbers allowed!"); } } </script> </head> <body> <input type="text" ...
🌐
Mredkj
mredkj.com › tutorials › validate.html
Tutorials - KeyPress validation - mredkj.com
The contents of this page are still ... onkeypress="return onKeyPressBlockNumbers(event);" /> </form> This example will block numbers by returning false to the onkeypress event handler....
🌐
Stack Overflow
stackoverflow.com › questions › 71177307 › how-do-i-validate-a-form-element-on-key-press
javascript - How do I validate a form element on key press? - Stack Overflow
February 18, 2022 - Please use onkeypress html attribute to call javascript function to validate field: w3schools.com/jsref/event_onkeypress.asp ... Thank you for your answer Roby Raju Oommen, I used onkeypress: nameInput.keypress(function(event) { ...
🌐
w3tutorials
w3tutorials.net › blog › trigger-a-keypress-keydown-keyup-event-in-js-jquery
How to Trigger Keypress, Keydown, Keyup Events in JavaScript/jQuery: Simulating User Input Handlers Without Actual Text Entry — w3tutorials.net
In web development, there are scenarios where you need to replicate user keyboard interactions programmatically—whether for testing, automated UI flows, accessibility validation, or simulating user input in demos. While users naturally press keys to interact with elements like inputs and buttons, developers often need to trigger these events *without actual text entry*. This blog dives deep into how to simulate `keydown`, `keyup`, and (deprecated but still relevant) `keypress` events using vanilla JavaScript and jQuery.