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
🌐
JavaScript Kit
javascriptkit.com › javatutors › javascriptkey3.shtml
Form validation using the keyboard events
Click here for comprehensive JavaScript tutorials, and over 400+ free scripts!
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

🌐
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 - Right-click on the project and select Add -> Web Form and name it as Home.aspx. 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>How to Validate Number using onkeypress in JavaScript</title> </head> <body> <form> <label class="label">Number Validation:</label> <input type="text" name="" onKeyPress="return ValidateAlpha(event);"> <script type="text/javascript"> function ValidateAlpha(evt){ var keyCode = (evt.which) ?
Find elsewhere
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;
}
🌐
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 ...
🌐
Mredkj
mredkj.com › tutorials › validate.html
Tutorials - KeyPress validation - mredkj.com
The HTML and JavaScript for Try It - Block Numbers is released to the public domain. Read the Terms of Use for details. The contents of this page are still copyrighted. function onKeyPressBlockNumbers(e) { var key = window.event ? e.keyCode : e.which; var keychar = String.fromCharCode(key); reg = /\d/; return !reg.test(keychar); } <form> <input type="text" onkeypress="return onKeyPressBlockNumbers(event);" /> </form>
Top answer
1 of 1
1

As per your comment. Instead of running validation again you can just add event listener that listens for Keydown (or Keyup) and then removes the class displaying the error.

const myform = document.getElementById("signinform");
myform.noValidate = true;

// custom form validation
myform.addEventListener("submit", validateForm);

// stop submission of valid form for demo
myform.addEventListener("submit", (e) => {
  e.preventDefault();

  const fd = new FormData(e.target);
  for (const [name, value] of fd.entries()) {
    console.log(name + ": " + value);
  }
});

// form validation
function validateForm(e) {
  const form = e.target,
    field = Array.from(form.elements);

  // reset fields
  field.forEach((i) => {
    i.parentElement.classList.remove("errore");
    i.parentElement.classList.add("success");
  });

  if (!form.checkValidity()) {
    // form is invalid - cancel submit
    e.preventDefault();
    e.stopImmediatePropagation();

    // apply invalid class
    field.forEach((i) => {
      if (!i.checkValidity()) {
        // field is invalid - add class
        i.parentElement.classList.add("errore");
        i.parentElement.classList.remove("success");
      }
    });
  }
}

//  remove the error class on Keydown input
const formInputs = document.querySelectorAll(".msc-login-form-input");
formInputs.forEach((input) => {
  input.addEventListener("keydown", () => {
    input.classList.remove("errore");
    input.classList.add("success");
  });
});
.msc-login-form-input {
  display: flex;
}
.msc-login-form-input.success > input {
  color: #3f4254;
  background-color: #ffffff;
}
.msc-login-form-input.errore > input {
  background-color: #4d40ff;
  color: #ffffff;
}
.msc-login-form-input.errore > input::-webkit-input-placeholder {
  color: #ffffff;
}
.msc-login-form-input.errore > input:-ms-input-placeholder {
  color: #ffffff;
}
.msc-login-form-input.errore > input::placeholder {
  color: #ffffff;
}
.msc-login-form-input > span {
  width: 35px;
  background-color: rgba(0, 0, 0, 0.05);
  min-height: 100%;
  align-items: center;
  justify-content: center;
  text-align: center;
  display: flex;
}
.msc-login-form-input > span::before {
  font-family: "Font Awesome 5 Free";
  font-weight: 900;
  content: "\f100";
}
.msc-login-form-input.success > span::before {
  content: "\f00c";
  color: #ff1493;
}
.msc-login-form-input.errore > span::before {
  content: "\f00d";
  color: #4d40ff;
}
<form id="signinform" method="post" action="#" class="wp-user-form" autocomplete="off">
  <div class="msc-login-form-input">
    <input type="text" name="log" value="" id="user_login" placeholder="prova" required/>
    <span></span> </div>
  <div class="msc-login-form-input">
    <input type="password" name="pwd" value="" id="user_pass" placeholder="prova" required/>
    <span></span> </div>
  <div class="msc-login-form-input-sendh">
    <input type="submit" id="submit-login" name="submit-login" value="Submit" class="user-submit" />
  </div>
</form>

Also your script tags should not be inside the form. They should be at the bottom of your page or in the <head> using async.

🌐
Stack Exchange
magento.stackexchange.com › questions › 268464 › jquery-validation-not-working-on-pressing-enter-key-in-magento2-2-5
jQuery validation not working on pressing enter key in Magento2.2.5? - Magento Stack Exchange
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script> <script type="text/javascript"> require([ 'jquery' ], function($){ // jQuery(document).ready(function(){ // jQuery('.input').keypress(function(e) { // if (e.which == 13) { // alert('ok'); // $('#custom-form').submit(); // return false; // } // }); jQuery(document).keypress(function(event){ var keycode = (event.keyCode ?
🌐
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) { ...