You can make your function run when the keypress event is fired with:

$("#purpose").on('keypress', validate);

However, using the keypress event on a text input is generally a bad idea. It doesn't work on mobile devices, and it doesn't trigger when Backspace or Delete is pressed or text is pasted or cut in or out of the input. You should probably use the input event instead:

$("#purpose").on('input', validate);
Answer from insert_name_here 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 - First, notice that I am listening on not only keypress but also keyup. This is because keypress does not fire when the user deletes a character but we still need to check the input value to be sure that it’s valid.
Discussions

validation - jquery - validate characters on keypress? - Stack Overflow
I have a form text field that I want to allow only numbers and letters in. (i.e., no #$!, etc...) Is there a way to throw up an error and prevent the keypress from actually outputting anything if... More on stackoverflow.com
🌐 stackoverflow.com
November 12, 2011
How do I validate a form element on key press?
I have code that validates a form before it is sent to the server and what I want to achieve is to validate the form elements on keypress. So, when the cursor is currently in a form element, I want... More on stackoverflow.com
🌐 stackoverflow.com
February 18, 2022
Javascript validation onkeypress function - Stack Overflow
In web form, I have multiple fields and each field have some unique validation like phone and zip code have only number and some of the fields do not allow special characters. So how do I validate ... More on stackoverflow.com
🌐 stackoverflow.com
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 Kit
javascriptkit.com › javatutors › javascriptkey3.shtml
Form validation using the keyboard events
Click here for comprehensive JavaScript tutorials, and over 400+ free scripts!
🌐
Stack Overflow
stackoverflow.com › questions › 71177307 › how-do-i-validate-a-form-element-on-key-press
How do I validate a form element on key press?
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) { ...
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

Find elsewhere
🌐
Jquery
forum.jquery.com › topic › keypress-validation
keypress validation
Ask questions here if you're new to jQuery or JavaScript and need help making sense of it all · Ask questions and report issues related to using jQuery. Discuss anything related to jQuery itself. For issues with plugins, ask in the jQuery Plugins forum · Want to discuss the forum itself?
Top answer
1 of 2
18

Validate on blur, or on submit. Don't validate while typing, for exactly the reason you describe.

There are studies/observations that show the people generally complete the entire form and then return to values that are incorrect. Even if you validate on blur they will tend to complete all fields and will then return to fix.

Article: Usable error message presentation in the World Wide Web: Do not show error right away Author: Javier A. Bargas-Avila, Glenn Oberholzer, Peter Schmutz, Marco de Vito, and Klaus Opwis Source: Interactive with Computers, Volume 19, pages 330-341 (2007)

Results of the Study

  • When Completing an online form users have two modes: Completion Mode and Revision Mode
  • Users tend to ignore immediate error messages when they are in Completion Mode
  • Of the size possible ways to present error messages, three proved to be more effective than the others:
    • Present the error afterward, embedded in the form, all at once
    • Present the error afterward, embedded in the form, one by one
    • Present the error afterward, in dialogues, one by one

The study alone suggests you should present error after the user has completed the form -- in other words, on submit.

If you validate on blur, show a simple non-obtrusive error (a highlight and possible a short message next to or under the field). Do not force the user to fix it immediately. You can disable the "submit" button until all fields are validated -- include a small message or popover indicating why the "submit" button is disabled (e.g., "Please fix the highlighted fields before submitting"). You can let the user submit despite errors too and display an additional error message then.

Note that you have to validate on submit if you want make sure you catch errors. Client side validation (i.e., on blur) requires JavaScript and JavaScript can be turned off. It is rare these days, but it is not unheard of. Also, not all browsers support the same level of JavaScript.

Validating on blur helps the user realize something is wrong before they submit, but you will also need to validate on submit to make absolutely sure everything is formatted the way you want it. However, the study quoted above would suggest that validating on blur does not buy you anything that validating on submit already provides.

2 of 2
5

As revealed in this fantastic article, the answer is on blur.

To quote:

When we used the “after” method in the first half of the form, participants completed the form seven to ten seconds faster than when we used the “while” and “before and while” methods respectively. Why? Here’s what happened when we used the “while” and “before and while” methods: When several participants noticed an error message while trying to answer a question, they entered one additional character into the input field, than waited for the message to update. If the updated message continued to show an error, they entered another character, then waited for the validation message to update again, and so on, resulting in longer average completion times.

The “before and while” method not only caused longer completion times, but also produced higher error rates and worse satisfaction ratings than the other inline validation variations we tested. Our participants articulated their strong distaste for this methodology:

“It’s frustrating that you don’t get the chance to put anything in [the field] before it’s flashing red at you.”

“When I clicked in the First Name field, it immediately came up saying that [my first name] is too short. Well of course it is! I haven’t even started!”

“I found it quite annoying how red crosses came up when you hadn’t finished typing. It’s just really distracting.”

These negative reactions, longer completion times, and error rates illustrate that validating inputs prematurely can be harmful. Instead, when you validate open-ended questions, give feedback after the user finishes providing an answer. Or in situations in which people need help sooner, give feedback while they work toward an answer, but use an appropriate delay so premature error messages don’t frustrate them.

🌐
C# Corner
c-sharpcorner.com › blogs › numeric-keypress-validation-in-textbox-using-javascript1
Numeric KeyPress Validation in TextBox using JavaScript
May 19, 2020 - In this blog we will learn to perform perform Numeric validation in TextBox on KeyPress using JavaScript which will accept only numeric digits in TextBox.
🌐
Pearson IT Certification
pearsonitcertification.com › articles › article.aspx
User Input Validation | Error Handling for the User Interface | Pearson IT Certification
However, you can modify this behavior. When you set the KeyPreview property of a form to True, the form will receive all three events (KeyDown, KeyPress, and KeyUp) just before the active control receives them. This allows you to set up a two-tier validation on controls.
🌐
DevExpress
supportcenter.devexpress.com › Ticket › Details › T623459 › angular-reactive-forms-forcing-validation-on-keypress
Angular Reactive Forms - Forcing validation on keypress | DevExpress Support
April 12, 2018 - I am working with a form and want to validate the input field as the user types (on keypress) instead of when the user navigates away from t
🌐
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();" />
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;
}