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:
13th Jul, 2024
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. (password length validation in javascript)
  • 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 and offers email and password validation in javascript 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, password validation regex using JavaScript’s 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

Conclusion

Ads of upGrad blog

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 which helps in password validation in javascript. 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.

4What is a function in JS?

A function in JavaScript is a reusable block of code designed to perform a specific task. Functions allow you to encapsulate logic, making your code more modular and easier to maintain. They can accept input in the form of parameters, process this input, and return an output. By defining functions, you can avoid code duplication, enhance readability, and facilitate debugging. Functions can be named or anonymous, and JavaScript also supports more modern syntaxes like arrow functions, providing flexibility in how functions are written and utilized within your programs.

Explore Free Courses

Suggested Blogs

Full Stack Developer Salary in India in 2024 [For Freshers &#038; Experienced]
907173
Wondering what is the range of Full Stack Developer salary in India? Choosing a career in the tech sector can be tricky. You wouldn’t want to choose
Read More

by Rohan Vats

15 Jul 2024

SQL Developer Salary in India 2024 [For Freshers &#038; Experienced]
902296
They use high-traffic websites for banks and IRCTC without realizing that thousands of queries raised simultaneously from different locations are hand
Read More

by Rohan Vats

15 Jul 2024

Library Management System Project in Java [Comprehensive Guide]
46958
Library Management Systems are a great way to monitor books, add them, update information in it, search for the suitable one, issue it, and return it
Read More

by Rohan Vats

15 Jul 2024

Bitwise Operators in C [With Coding Examples]
51783
Introduction Operators are essential components of every programming language. They are the symbols that are used to achieve certain logical, mathema
Read More

by Rohan Vats

15 Jul 2024

ReactJS Developer Salary in India in 2024 [For Freshers &#038; Experienced]
902674
Hey! So you want to become a React.JS Developer?  The world has seen an enormous rise in the growth of frontend web technologies, which includes web a
Read More

by Rohan Vats

15 Jul 2024

Memory Allocation in Java: Everything You Need To Know in 2024-25
74112
Starting with Java development, it’s essential to understand memory allocation in Java for optimizing application performance and ensuring effic
Read More

by Rohan Vats

12 Jul 2024

Selenium Projects with Eclipse Samples in 2024
43493
Selenium is among the prominent technologies in the automation section of web testing. By using Selenium properly, you can make your testing process q
Read More

by Rohan Vats

10 Jul 2024

Top 10 Skills to Become a Full-Stack Developer in 2024
229999
In the modern world, if we talk about professional versatility, there’s no one better than a Full Stack Developer to represent the term “versatile.” W
Read More

by Rohan Vats

10 Jul 2024

Polymorphism In OOPS: What is Polymorphism [Detailed Explanation]
129579
What is Polymorphism in OOPS? Polymorphism in OOPs is inseparable and an essential concept of every object-oriented programming language. An object o
Read More

by Rohan Vats

07 Jul 2024

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