Password Validation in JavaScript [Step by Step Setup Explained]

Any website that supports authentication and authorization always asks for a username and password through login. If not so, the user needs to register and create a password to login into the next session, and hence websites tend to provide specific protocols or parameters. The following parameters are commonly used for password validation in any form.

  • Only alphanumeric inputs are accepted in the password field.
  • It should start with the uppercase alphabet.
  • At Least one uppercase alphabet password.
  • The password should be of a specific length.
  • One numeric value must be used in the password.
  • The password must have a minimum and maximum length.

Password validation in JavaScript ensures that these parameters are followed when the user creates a password. The given conditions must be met for the formation of a reasonably strong password. The structure of the password can be validated by regular expression using JavaScript code.

Check out our free courses to get an edge over the competition.

Explore Our Software Development Free Courses

Our learners also read: Learn java free!

For processing the password validation in JavaScript in the password field, I have provided the step-by-step process that you have to follow.

Password Validation in Javascript

1. Create an HTML Form

The form should have basic fields like email, phone number and password. Let’s see an example of HTML code to define the structure of the form.

<!DOCTYPE html>

<html lang=“en”>


    <meta charset=“UTF-8”>

    <meta name=“viewport” content=“width=device-width, initial-scale=1.0”>




    <div class=“container”>

        <form action=“/action_page.php”>

          <label for=“usrname”>Email Address</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”>



      <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>16 characters</b></p>




Check out upGrad: Advanced Certification in DevOps

Explore our Popular Software Engineering Courses

2. Add CSS

input {

    width: 100%;

    padding: 12px;

    border: 1px solid #ccc;

    border-radius: 4px;

    box-sizing: border-box;

    margin-top: 6px;

    margin-bottom: 16px;


  /* Style the submit button */

  input[type=submit] {

    background-color: #4CAF50;

    color: white;


  /* Style the container for inputs */

  .container {

    background-color: #f1f1f1;

    padding: 20px;


  #message {


    background: #f1f1f1;

    color: #000;

    position: relative;

    padding: 20px;

    margin-top: 10px;


  #message p {

    padding: 10px 35px;

    font-size: 18px;


  .valid {

    color: rgb(3, 184, 190);


  .valid:before {

    position: relative;

    left: -35px;

    content: “✔”;


  .invalid {

    color: red;


  .invalid:before {

    position: relative;

    left: -35px;

    content: “✖”;


Checkout: Top Javascript Frameworks in 2021

Check Out upGrad Java Bootcamp

upGrad’s Exclusive Software and Tech Webinar for you –

SAAS Business – What is So Different?


3. Add JavaScript

var myInput = document.getElementById(“psw”);

var letter = document.getElementById(“letter”);

var capital = document.getElementById(“capital”);

var number = document.getElementById(“number”);

var length = document.getElementById(“length”)

myInput.onfocus = function() {

  document.getElementById(“message”).style.display = “block”;


myInput.onblur = function() {

  document.getElementById(“message”).style.display = “none”;


myInput.onkeyup = function() {

    var lowerCaseLetters = /[a-z]/g;

  if(myInput.value.match(lowerCaseLetters)) {



  } else {




var upperCaseLetters = /[A-Z]/g;

  if(myInput.value.match(upperCaseLetters)) {



  } else {




  var numbers = /[0-9]/g;

  if(myInput.value.match(numbers)) {



  } else {




  if(myInput.value.length >= 8) {



  } else {





The JavaScript code initially gets an element by the id; after that, it allows it to display on screen. It also runs conditions to get the password in the given format. The uppercase alphabets, lowercase alphabets and numbers are validated through the regular expression created in code.

Learn Java Tutorials

4. Regular Expressions/REGEX

 Regular expressions are patterns to match the original combination of literals passed in the field. In password validation, using JavaScript’s regular expression plays an essential role in identifying the string and whether it is in the given format or not. Regular expressions are JavaScript objects. These regular expressions are written in between slashes in JavaScript code for password validation.

Example: let re=/ac-b/

How to Write Password Validation in JavaScript Using Regular Expression?

A regular expression is formed of simple characters combined with special characters. The regular expression is formed according to the parameters or constraints of a strong password. Special characters are used when there exist a tough match of strings or characters.

The JavaScript code depicted above-made use of regular expressions to find upper case alphabets, lower case alphabets and numbers. The expression is made with different sequences and subsequences. There are certain rules for each character that is used in the regular expression. 

Example: let number=/[0-9]/g. It accepts the numbers in the range of 0-9.

Checkout: Javascript Projects in Github

Learn Software Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

Read our Popular Articles related to Software Development


In conclusion, mastering Password Validation in JavaScript equips mid-career professionals with skills for enhancing web security and user experience. Through the step-by-step guide provided, from creating an HTML form and styling it with CSS to adding the JavaScript logic and understanding the application of Regular Expressions (REGEX), we’ve seen how accessible and impactful this practice can be. Writing password validation using REGEX in JavaScript not only ensures that user inputs meet predefined security criteria but also lays a foundation for building more secure web applications. As professionals committed to the development of robust web solutions, incorporating these techniques into your projects is essential. This guide aims to simplify the process, enabling you to implement effective password validation strategies that safeguard user information and comply with security best practices. By harnessing the power of JavaScript and REGEX, you’re well-equipped to tackle the challenges of web security and enhance the integrity of your online platforms. 

If you’re interested to learn more about full-stack development, check out upGrad & IIIT-B’s Executive PG Program in Full-stack Software Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.

How to do password validation in JavaScript?

JavaScript provides a simple way to validate passwords. You will first have to create a regular expression to validate the password. You can use the function RegExp. test to check the validation of a password. Some possible validations can be – the password should have a minimum of 8 characters, it should be a mix of uppercase, lowercase, digits, etc., or it should have at least one special character. In fact, when the user enters the password through the form, you can display an option to generate custom password. Based on the input, you can suggest the user the complexity of the password that they have entered.

What is regular expression in programming?

Regular expressions are a concise and flexible way to find and manipulate text within strings. They are used in many areas of computer programming, including applications that search, process, and monitor text. Many programming languages have routine built in support for regular expressions. There is a huge difference between regular expressions and ordinary expressions in programming. By a regular expression we mean a sequence of characters and by ordinary expression we mean a sequence of characters. Thus, regular expression is a pattern that is to be matched, whereas ordinary expression means a pattern that is to be replaced. Regular expression is a kind of grammar.

What are the features of JavaScript programming language?

JavaScript is the most popular client-side scripting language for Web development for a number of reasons. It is lightweight, simple, and a component of the most popular Web browser. It is used to make Web pages dynamic, i.e. interactive, by adding client-side animation and event handling. JavaScript may be used to create both Web-based and desktop applications.

Want to share this article?

Land on Your Dream Job

Leave a comment

Your email address will not be published. Required fields are marked *

Our Popular Software Engineering Courses

Get Free Consultation

Leave a comment

Your email address will not be published. Required fields are marked *

Get Free career counselling from upGrad experts!
Book a session with an industry professional today!
No Thanks
Let's do it
Get Free career counselling from upGrad experts!
Book a Session with an industry professional today!
Let's do it
No Thanks