Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconFull Stack Developmentbreadcumb forward arrow iconPassword Validation in JavaScript [Step by Step Setup Explained]

Password Validation in JavaScript [Step by Step Setup Explained]

Last updated:
19th Feb, 2021
Read Time
7 Mins
share image icon
In this article
Chevron in toc
View All
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!

Ads of upGrad blog

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

Ads of upGrad blog

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.


Rohan Vats

Blog Author
Software Engineering Manager @ upGrad. Passionate about building large scale web apps with delightful experiences. In pursuit of transforming engineers into leaders.

Frequently Asked Questions (FAQs)

1How 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.

2What 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.

3What 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.

Explore Free Courses

Suggested Blogs

8 Exciting Full Stack Coding Project Ideas &amp; Topics For Beginners
A Full stack developer is an engineer who can design and develop an end-to-end application independently by handling all the work of coding, databases
Read More

by upGrad

19 Feb 2024

17 Interesting HTML Project Ideas &#038; Topics For Beginners [2024]
Summary In this article, you will learn 10 Interesting HTML Project Topics. Take a glimpse below. A tribute page A survey form Technical documentati
Read More

by Rohan Vats

19 Feb 2024

How to Open json File in Excel
What is JSON? JSON (JavaScript Object Notation) is a file format that is used for storing and exchanging data in the network. It is used to send data
Read More

by Rohan Vats

19 Feb 2024

JSP vs Servlet: Difference Between JSP &#038; Servlet [2024]
Websites are collections of static files, for example, images, graphics, and HTML files. These websites are referred to as web applications if they pr
Read More

by Rohan Vats

19 Feb 2024

Java Developer Salary in India in 2024 [For Freshers &#038; Experienced]
Wondering what is the range of Java developer salary in India? From choosing your first programming language to writing apps for Android and several
Read More

by Rohan Vats

19 Feb 2024

Polymorphism In OOPS: What is Polymorphism [Detailed Explanation]
Polymorphism in OOPs is inseparable and an essential concept of every object-oriented programming language. An object or reference basically can take
Read More

by Rohan Vats

19 Feb 2024

Literals In Java: Types of Literals in Java [With Examples]
Summary: In this article, you will learn about Literals in Java. Literals in Java Integral Literals Floating-Point Literals Char Literals String Lit
Read More

by Rohan Vats

19 Feb 2024

Top 30 Exception Handling Interview Questions and Answers [For Freshers &amp; Experienced]
Exception handling is a concept that is implemented in algorithms to handle possible runtime errors, which may disrupt the normal flow of a program. S
Read More

by Rohan Vats

19 Feb 2024

Top 40 MySQL Interview Questions &#038; Answers For Beginners &#038; Experienced [2024]
Have a Data engineering or data science interview coming up? Need to practice some of the most asked MySQL interview questions? The article compiles t
Read More

by Rohan Vats

19 Feb 2024

Schedule 1:1 free counsellingTalk to Career Expert
footer sticky close icon