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
🌐
JavaScript Kit
javascriptkit.com › javatutors › javascriptkey3.shtml
Form validation using the keyboard events
Click here for comprehensive JavaScript tutorials, and over 400+ free scripts!
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
Are there other ways to capture the user inputs other than keydown event before browser displays it? And a way to put the validation on it? ... 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 ... 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 - Form validation on keypress jquery - Stack Overflow
You should probably use the input event instead: ... Feedback requested: How do you use tag hover descriptions for curating and do... ... Children in a field trapped under a transparent dome who interact with a strange machine inside their car · how do I fix apt-file? - not working and added extra repos more hot questions ... To subscribe to this RSS feed, copy and paste this URL into ... More on stackoverflow.com
🌐 stackoverflow.com
November 12, 2017
🌐
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 - Keypress: fired when the key which is being pressed results in a character being sent. So this excludes modifier keys, directional keys, and keys which remove text. Keyup: fired after the user has released the key, telling you what key was pressed ...
🌐
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;
}
Find elsewhere
🌐
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 - Paste the following JavaScript function in the head section of the Home.aspx page. ... <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Home.aspx.cs" Inherits="NumericKeyPressValidation.Home" %> ... Numeric Value: <input type="text" id="text1" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;" />
🌐
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>Only Alphabets Validation using regex.</title> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> </head> <body> <label>Enter Mobile Number</label> <input type="text" id="txtName" maxlength="10" /> <span id="lblError" style="color: red"></span> <script type="text/javascript"> $(function () { $("#txtName").keypress(function (e) { var keyCode = e.keyCode || e.which; $("#lblError").html(""); //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

🌐
YouTube
youtube.com › technical rajni
Allow only numbers validation on KeyPress in TextBox with Javascript - YouTube
Please do like share and comment if you like the video please do hit like and if you have any query please write it comment box NestJs Tutorial https://www.y...
Published   June 7, 2023
Views   673
🌐
TutorialsPoint
tutorialspoint.com › article › What-is-onkeypress-event-in-JavaScript
What is onkeypress event in JavaScript?
<html> <head> <script> function ... something..."> </body> </html> You can access the pressed key information using the event object: <html> <head> <script> function handleKeypress(event) { const key = event.key; const ...
🌐
OutSystems
outsystems.com › forums › discussion › 92866 › email-validation-on-keypress
Email Validation on keypress | OutSystems
I need to validate the email from the client side. So, I have configured validation, and it is working. but now I want to restrict the user from entering special characters other than the required format · I have implement the JavaScript which restrict the special characters and only allow ...
🌐
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) { ... , but it ...