• 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);".

Answer from Schism on Stack Exchange
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 2
1

Use .on("keypress",function(){}) as written to the code below:

$("#password").on("keyup",function(){
    if($(this).val().length < 9 && $(this).val().length != 0 ){
      $("#lblError").prop("style","display:block");
      $("#Submit").prop("style","display:none");
    }
    else if($(this).val().length == 0){
      $("#Submit").prop("style","display:none");
      $("#lblError").prop("style","display:none");
    }
    else{
     $("#Submit").prop("style","display:block");
     $("#lblError").prop("style","display:none");
    }
})
<html>

<head>
  <title>Email List</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <style type="text/css">
    * {
      margin: 0;
      padding: 0;
      font-family: Arial;
      box-sizing: border-box
    }
    
    body {
      text-align: center;
    }
    
    header {
      padding: 50px;
      color: black;
      font-size: 20pt
    }
    
    section {
      width: 700px;
      margin: 0 auto;
    }
    
    ul {
      margin: 0;
      padding: 0;
      list-style: none;
      box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19), 0 6px 6px rgba(0, 0, 0, 0.23);
    }
    
    ul li {
      cursor: pointer;
      position: relative;
      padding: 12px 8px 12px 40px;
      background: #FF6D1F;
      font-size: 18px;
      transition: 0.2s;
      text-align: left;
      user-select: none;
    }
    
    ul li:nth-child(odd) {
      background: #FA5B0F;
    }
    
    ul li:hover {
      background: #FF822E;
    }
    
    ul li.checked {
      background: #FF822E;
      color: #fff;
      text-decoration: line-through;
    }
    
    ul li.checked::before {
      content: '';
      position: absolute;
      border-color: #fff;
      border-style: solid;
      border-width: 0 2px 2px 0;
      top: 10px;
      left: 16px;
      transform: rotate(45deg);
      height: 15px;
      width: 7px;
    }
    
    .close {
      position: absolute;
      right: 0;
      top: 0;
      padding: 12px 16px 12px 16px;
      display: none;
      background-color: #f44336;
    }
    
    .close:hover {
      color: white;
    }
    
    form {
      padding: 0;
      margin-top: 20px;
      width: 100%;
      overflow: hidden;
    }
    
    input {
      height: 56px;
      line-height: 56px;
      margin-right: 0;
      display: inline-block;
      float: left;
      width: 90%;
      font-size: 18px;
      padding: 12px 8px 12px 40px;
      outline: 0;
    }
    
    .btn {
      display: inline-block;
      background-color: green;
      width: 10%;
      padding: 9.5px;
      font-size: 32px;
      cursor: pointer;
      background-color: #FA5B0F;
    }
    
    .btn:hover {
      color: white;
      background-color: #ff931e;
    }
    
    #lblError {
      background-color: #000;
      color: white;
      height: 56px;
      line-height: 56px;
      display: none;
    }
    #Submit {
      color: white;
      height: 56px;
      line-height: 56px;
      display: none;
    }
  </style>
</head>

<body>
  <header>
    <h1>Create A New Password</h1>
  </header>

  <section>


    <form>
      <input type="password" id="password" placeholder="Enter a password" autocomplete="off">

    </form>

    <div id="lblError">Please enter a password longer than 9 characters!</div>
    <div id="Submit"><input type="submit"></div>
  </section>

</html>

Feel free to ask for any clarification.

2 of 2
1

You can also try using pure javascript to accomplish this.

var minLength = 9;
var output = document.getElementById("output");

function checkInput(){
    var password = document.getElementById("password").value;
    if (password.length < minLength) {
         output.innerHTML = "Not yet.....";
         return false; 
    }else {
         output.innerHTML = "<button>submit</button>";
      }
}
    <form>
      <input type="password" id="password" placeholder="Enter a password" autocomplete="off" onkeyup="checkInput()">
      <p id="output"></p>
    </form>

Discussions

php - password mismatch alert javascript on onkeypress - Stack Overflow
I want to check whether confirm password matches with password or not, through onkeypress() function. It's not working.. Some of the part working like password length must be 6 character. But, I'm ... More on stackoverflow.com
🌐 stackoverflow.com
September 2, 2015
javascript - on keyup event of password field validation should perform - Stack Overflow
Form validation using jquery Onkeyup event password input field is verified as minimum 8 character one lower case letter,one upper case letter,one numeric and one special character More on stackoverflow.com
🌐 stackoverflow.com
June 7, 2015
Alphanumeric password validation in javascript - Stack Overflow
I have written function in javascript for alphanumeric password validation in jsp and calling that function on onkeypress event of textbox but not working. function alphanumeric(inputtxt) { ... More on stackoverflow.com
🌐 stackoverflow.com
December 3, 2016
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
🌐
W3Schools
w3schools.com › howto › howto_js_password_validation.asp
How To Create a Password Validation Form
Learn how to create a password validation form with CSS and JavaScript. ... <div class="container"> <form action="/action_page.php"> <label for="usrname">Username</label> <input type="text" id="usrname" name="usrname" required> <label for="psw">Password</label> < input type="password" id="psw" name="psw" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" title="Must contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters" required> <input type="submit" value="Submit"> </form> </div> <div id="message"> <h3>Password must contain the following:</h3> <p id="letter" class="invalid">A <b>lowercase</b> letter</p> <p id="capital" class="invalid">A <b>capital (uppercase)</b> letter</p> <p id="number" class="invalid">A <b>number</b></p> <p id="length" class="invalid">Minimum <b>8 characters</b></p> </div>
🌐
Stack Overflow
stackoverflow.com › questions › 30690160 › on-keyup-event-of-password-field-validation-should-perform
javascript - on keyup event of password field validation should perform - Stack Overflow
June 7, 2015 - function validatePassword() { var password = $("#password").val(); if (password.match(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@%!])[0-9a-zA-Z@%!]{8,}$/)) $("#divPasswordValidationResult").html("pass"); else $("#divPasswordValidationResult").html("fail"); } $(document).ready(function () { $("#password").keyup(validatePassword); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="td"> <input type="password" id="password" /> </div> <div class="registrationFormAlert" id="divPasswordValidationResult"> </div>
🌐
Keithhatfield
keithhatfield.com › home › simple javascript password validation
Simple Javascript Password Validation | Keith Hatfield Development
September 4, 2019 - If you ever want to change which inputs are checked or remove the validation completely, you only have one place to edit. ... There’s a lot that you could do to extend the functionality of this simple script. Changing the colors is a great visual identifier for the user, but for added security, the script could be extended to disable the form submit button or alert the user before they submit the form if the passwords do not match.
Find elsewhere
🌐
ASPSnippets
aspsnippets.com › Articles › 1256 › Password-Strength-validation-example-using-JavaScript-and-jQuery
Password Strength validation example using JavaScript and jQuery
June 4, 2015 - explained how to implement Password Strength validation for Password TextBox with examples in JavaScript and jQuery. The Password strength validation in JavaScript and jQuery will be performed using Regular Expressions (Regex).
🌐
Upgrad
upgrad.com › home › blog › software development › everything you need for effective password validation in javascript!
Enhance Security with Password Validation in JavaScript Now!
July 9, 2025 - This blog covers step-by-step password validation in · JavaScript, including rules, real-time feedback, and practical code examples for enhanced form functionality.
🌐
W3Resource
w3resource.com › javascript › form › password-validation.php
JavaScript : Password validation - w3resource
August 19, 2022 - To validate the said format we use the regular expression ^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{4,8}$. Next the match() method of string object is used to match the said regular expression against the input value.
🌐
The Art of Web
the-art-of-web.com › javascript › validate-password
Password Validation using regular expressions and HTML5
Using JavaScript to confirm username and password input format. Examples of form validation using both simple and complex regular expressions. Restricting to alphanumeric and letter characters.
🌐
Envato Tuts+
webdesign.tutsplus.com › home › web design › html/css › javascript for designers
Write Your Own Password Validation with JavaScript | Envato Tuts+
September 8, 2023 - How to Implement Debounce and Throttle with JavaScript ... If the value of the confirm password field is not empty and is not equal to the password field value on blur, then we display the password match error message. We can also use a focus event listener to handle hiding the error message when the user starts typing again. Next, we want to handle validating the password as the user types it in.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › password-validation-form-using-javascript
Password Validation Form Using JavaScript - GeeksforGeeks
April 18, 2025 - JavaScript Code: It handles password validation in a web form and performs the checks on the password input field and updates the corresponding password message items based on certain criteria.
Top answer
1 of 2
1

If the passwords match, it will skip your entire else block:

 //confirm passwords match and have been created
    if ((passForm.passInput.value) == (passForm.confirmPassInput.value)) {
        alert("Your password has been created!");

    } else {
       //you are doing validation here.

You need to run multiple checks:

window.onload = function() {

    var subButton = document.getElementById("submit");
   subButton.onclick = function value(passForm) {

   }

};



function value(passForm) {

    /** This function is being used to find out the values input by the user in both the password and confirm password text boxes.
     * The results are fed back to the user using alerts.
     * **/

   //check for lower case
        if (!passForm.passInput.value.match(/[a-z]/)) {
            alert("Password must contain at least one lower case letter.");
            passForm.passInput.focus();
            return false;
        }
        
        //Validating length
        if ((passForm.passInput.value).length < 8) {
            alert("Your password has less than 8 characters.");
            passForm.passInput.focus();
            return false;
        }
        
        //Validationg confirmation matches
        if (passForm.confirmPassInput.value != passForm.passInput.value) {
            alert("Your confirmation password does not match.");
            passForm.passInput.focus();
            return false;
        }
   
   //Validating confirmation input
        if (passForm.confirmPassInput.value == "") {
            alert("Please confirm your password.");
            passForm.passInput.focus();
            return false;
        }
   
   //check for upper ase
        if (!passForm.passInput.value.match(/[A-Z]/)) {
            alert("Password must contain at least one upper case letter.");
            passForm.passInput.focus();
            return false;
        }
        
           //check for number
        if (!passForm.passInput.value.match(/\d+/g)) {
            alert("Password must contain at least one number.");
            passForm.passInput.focus();
            return false;
        }
        
   
   //confirm passwords match and have been created
    if ((passForm.passInput.value) == (passForm.confirmPassInput.value)) {
        alert("Your password has been created!");
 return true;
    }
       

    };
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script type="text/javascript" src="js/security.js"></script>
    <title>E-Commerce Security Features</title>
</head>
<body>
<heading>
    <h1>E-Commerce Security Practices</h1>
    <p id="heading"></p>
</heading>

<h3> Welcome to the E-Commerce Security Practices page! Here you will complete a few <i>simple</i> website security procedures and then decide
    what practice worked best and easiest for you. </br> Have fun!</h3>
<form name="passForm" method="post" onsubmit="return value (this)">
<p>In the section below, you are asked to create a username and a password in order to 'login'. </br> Your password <b>must</b> include 8 or more
characters, an upper and lower case letter and a number and a symbol. If your password does not include any of these requirements, it will not be accepted.</p>
Your Password: <input type="password" name="passInput" placeholder="Password" /> 
</br>
    Confirm Password: <input type="password" name="confirmPassInput" placeholder="Re-Enter Password"/>
<input type="submit" value="Submit" id="submit" onclick="return value (passForm) ;"/>
</form>
</body>
</html>

2 of 2
0

I guess you need to use regular expression look like

 (/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/)

Minimum eight characters, at least one letter, one number and one special character:

 "^(?=.*[A-Za-z])(?=.*\d)(?=.*[$@$!%*#?&])[A-Za-z\d$@$!%*#?&]{8,}$""^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$"

Minimum eight characters, at least one uppercase letter, one lowercase letter, one number and one special character:

"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{8,}"

Minimum eight and maximum 10 characters, at least one uppercase letter, one lowercase letter, one number and one special character:

"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{8,10}"
🌐
DEV Community
dev.to › sharathchandark › password-validation-check-in-html-css-javascript-show-hide-password-toggle-4d7c
Password Validation Check in HTML CSS & JavaScript | Show Hide Password Toggle - DEV Community
December 31, 2024 - By the end of this video, you'll have a powerful password validator tool that will check the security-conscious, like whether the user-entered password contains at least 8 characters long, 1 uppercase and 1 lowercase, and at least 1 number and special character. This will make our password strong and effortless. Let's get started on creating your own javascript-powered password validator app now!