View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Introduction to Password Validation in JavaScript [Step by Step Setup Explained]

By Rohan Vats

Updated on May 22, 2025 | 7 min read | 50.49K+ views

Share:

Did you know? In 2025, JavaScript continues to evolve with the rise of server-first frameworks, the dominance of TypeScript, and the integration of AI and WebAssembly. These shifts keep JavaScript at the core of web and mobile development, proving its adaptability and long-term value for developers.

Password validation in JavaScript is essential for securing user data and improving form reliability. By using JavaScript, you can check if a password meets specific criteria like length, special characters, or uppercase letters before it is submitted, enhancing both security and user experience.

In this blog, you’ll learn how to set up password validation in JavaScript step by step using JavaScript. You will see the basic rules, real-time feedback, and practical code examples to help you build stronger, more user-friendly forms for your web projects.

Want to enhance your development skills? upGrad’s Online Software Development Courses provide you with the latest tools and strategies to stay ahead in the ever-evolving tech world. Enroll today and build the future of web development!

 

Implementing Password Validation in JavaScript

Password validation in JavaScript can be implemented using custom conditions such as minimum length, inclusion of numbers, special characters, and uppercase letters. You can validate passwords in real time as users type or before form submission.

If you want to gain expertise in programming languages, the following courses from upGrad can help you. 

Let’s see each password validation in JavaScript rule step by step, with clear code examples, output previews, and explanations of how different checks improve password strength and user security.

1. Creating the 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>

Coverage of AWS, Microsoft Azure and GCP services

Certification8 Months

Job-Linked Program

Bootcamp36 Weeks

Also Read: Top 25+ HTML Project Ideas for Beginners in 2025: Source Code, Career Insights, and More

2. Styling to the Form with CSS

In this step, we’ll add CSS to style the form and enhance its visual clarity. Styling helps users easily identify input fields, error messages, and the overall layout, making the form more user-friendly and accessible. Applying CSS ensures the form looks clean, responsive, and visually aligned with modern web design practices.

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: "✖";

  }
</> Copy Code

Join the "JavaScript Basics from Scratch" course by upGrad. Learn core concepts like variables, data types, functions, loops, and event handling in a beginner-friendly way. Build interactive website features and overcome common web development challenges with hands-on experience.

Checkout: Top Javascript Frameworks in 2021

3. Validating with JavaScript

In this step, you'll add JavaScript to handle real-time password validation logic based on specific rules, such as minimum length, uppercase letters, numbers, and special characters. This script dynamically checks the user's input as they type and gives instant feedback. Adding JavaScript at this point makes the form interactive and ensures that the password meets all required criteria before submission, improving user experience and security.

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

  }

}
</> Copy Code

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.

Also Read: Top 50 Most Asked Javascript Interview Questions in 2025

4. Understanding Regular Expressions/REGEX

 Regular expressions (commonly known as RegEx) are powerful tools used in JavaScript for pattern matching. In the context of password validation, RegEx helps enforce specific rules such as requiring a mix of uppercase letters, lowercase letters, numbers, and special characters. These patterns help developers ensure users set strong, secure passwords that reduce the risk of unauthorized access.

A regular expression is defined using either slash notation or the RegExp() constructor:

let regex = /[A-Z]/; // Slash notation
let regexAlt = new RegExp('[A-Z]'); // Using constructor

These expressions are used with .test() or .match() methods to validate strings.

Why Use RegEx for Password Validation?

RegEx allows you to write compact and efficient validation logic that checks whether a password meets specific security requirements, without writing complex loops or conditionals.

For example, to check if a password contains at least one number:

let password = "test123";
let hasNumber = /[0-9]/.test(password); // returns true

What RegEx Helps With in Password Validation

  • Prevents weak passwords like password123
  • Reduces the number of bad inputs before reaching the backend
  • Improves form responsiveness with instant validation
  • Standardizes input formats across applications

Full Password Validation in JavaScript Example Using RegEx:

function validatePassword(password) {
  const hasUppercase = /[A-Z]/.test(password);
  const hasLowercase = /[a-z]/.test(password);
  const hasNumber = /[0-9]/.test(password);
  const hasSpecialChar = /[!@#$%^&*]/.test(password);
  const isLongEnough = password.length >= 8;

  return hasUppercase && hasLowercase && hasNumber && hasSpecialChar && isLongEnough;
}

Code Explanation: This function checks that the password is strong according to five criteria.

Output:

true

Final Output:

Check out: Javascript Projects in Github

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 you’ve seen how accessible and impactful this practice can be which helps in password validation in javascript. 

Writing password validation using REGEX in JavaScript ensures that user inputs meet predefined security criteria and lays a foundation for building more secure web applications.

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.

Frequently Asked Questions (FAQs)

1. How do I set up real-time password validation using JavaScript and regex?

2. What’s the ideal learning path for mastering regex for form validation in JavaScript?

3. Why is my JavaScript regex not matching certain special password characters?

4. How do I combine multiple password validation rules into one regex pattern in JavaScript?

5. Can I visually show which password rules are met using JavaScript and CSS?

6. What project should I build to solidify my understanding of password validation with regex?

7. Why does the regex I wrote in regex101 work fine there but fail in JavaScript?

8. How do I validate both the password and confirm password fields in JS without confusion?

9. Are there any open-source UI components or libraries for password validation in JS?

10. What’s a recommended regex pattern for password validation that balances security and usability?

11. How can I write automated tests for my custom password validation function in JavaScript?

References:

  • https://www.linkedin.com/pulse/what-lies-ahead-javascript-predictions-2025-srikanth-r-teqjc/

Rohan Vats

408 articles published

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

Get Free Consultation

+91

By submitting, I accept the T&C and
Privacy Policy

India’s #1 Tech University

Executive PG Certification in AI-Powered Full Stack Development

77%

seats filled

View Program

Top Resources

Recommended Programs

upGrad

AWS | upGrad KnowledgeHut

AWS Certified Solutions Architect - Associate Training (SAA-C03)

69 Cloud Lab Simulations

Certification

32-Hr Training by Dustin Brimberry

upGrad

Microsoft | upGrad KnowledgeHut

Microsoft Azure Data Engineering Certification

Access Digital Learning Library

Certification

45 Hrs Live Expert-Led Training

upGrad

upGrad KnowledgeHut

Professional Certificate Program in UI/UX Design & Design Thinking

#1 Course for UI/UX Designers

Bootcamp

3 Months