Blog_Banner_Asset
    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
Views
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”>

<head>

    <meta charset=“UTF-8”>

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

    <title>Form</title>

</head>

<body>

    <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”>

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

      </div>

</body>

</html>

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 {

    display:none;

    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)) {

    letter.classList.remove(“invalid”);

    letter.classList.add(“valid”);

  } else {

    letter.classList.remove(“valid”);

    letter.classList.add(“invalid”);

}

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

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

    capital.classList.remove(“invalid”);

    capital.classList.add(“valid”);

  } else {

    capital.classList.remove(“valid”);

    capital.classList.add(“invalid”);

  }

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

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

    number.classList.remove(“invalid”);

    number.classList.add(“valid”);

  } else {

    number.classList.remove(“valid”);

    number.classList.add(“invalid”);

  }

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

    length.classList.remove(“invalid”);

    length.classList.add(“valid”);

  } else {

    length.classList.remove(“valid”);

    length.classList.add(“invalid”);

  }

}

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

Conclusion

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.

Profile

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

Top 7 Node js Project Ideas &#038; Topics
31659
Node.JS is a part of the famous MEAN stack used for web development purposes. An open-sourced server environment, Node is written on JavaScript and he
Read More

by Rohan Vats

05 Mar 2024

How to Rename Column Name in SQL
47022
Introduction We are surrounded by Data. We used to store information on paper in enormous file organizers. But eventually, we have come to store it o
Read More

by Rohan Vats

04 Mar 2024

Android Developer Salary in India in 2024 [For Freshers &#038; Experienced]
901414
Wondering what is the range of Android Developer Salary in India? Software engineering is one of the most sought after courses in India. It is a reno
Read More

by Rohan Vats

04 Mar 2024

7 Top Django Projects on Github [For Beginners &amp; Experienced]
52388
One of the best ways to learn a skill is to use it, and what better way to do this than to work on projects? So in this article, we’re sharing t
Read More

by Rohan Vats

04 Mar 2024

Salesforce Developer Salary in India in 2024 [For Freshers &#038; Experienced]
909375
Wondering what is the range of salesforce salary in India? Businesses thrive because of customers. It does not matter whether the operations are B2B
Read More

by Rohan Vats

04 Mar 2024

15 Must-Know Spring MVC Interview Questions
34816
Spring has become one of the most used Java frameworks for the development of web-applications. All the new Java applications are by default using Spr
Read More

by Arjun Mathur

04 Mar 2024

Front End Developer Salary in India in 2023 [For Freshers &#038; Experienced]
902454
Wondering what is the range of front end developer salary in India? Do you know what front end developers do and the salary they earn? Do you know wh
Read More

by Rohan Vats

04 Mar 2024

Method Overloading in Java [With Examples]
26542
Java is a versatile language that follows the concepts of Object-Oriented Programming. Many features of object-oriented programming make the code modu
Read More

by Rohan Vats

27 Feb 2024

50 Most Asked Javascript Interview Questions &#038; Answers [2024]
4545
Javascript Interview Question and Answers In this article, we have compiled the most frequently asked JavaScript Interview Questions. These questions
Read More

by Kechit Goyal

26 Feb 2024

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