Validating a password using JavaScript


The importance of robust password validation cannot be overstated in today's digital landscape, where online security is of paramount concern. Ensuring that user passwords meet certain criteria, such as complexity and length requirements, is vital in safeguarding sensitive information from unauthorized access. JavaScript, a versatile scripting language, provides developers with the necessary tools to implement effective password validation mechanisms. In this article, we delve into the intricate process of validating a password using JavaScript, elucidating the underlying algorithms and rarely utilized functions that empower developers to enhance the security of their web applications. By mastering this skill, developers can fortify their applications against potential vulnerabilities and bolster user confidence in their digital endeavors.

Problem Statement

The problem at hand entails the development of a JavaScript function responsible for validating passwords. The function should adhere to specific criteria −

  • the password must be between 6 and 20 characters in length

  • must include a digit

  • a lowercase English character

  • an uppercase English character

  • a special character. The set of special characters encompassed comprises the following: !@#$%^&*()-+.

To further elucidate the problem, let us consider an example. Suppose the function receives the password

"Ex@mpl3!"

The function should return a value indicating the validity of the password. In this case, the expected output would be

true

as the given password satisfies all the aforementioned conditions.

Approach

In this article, we are going to see a number of different ways to solve the above problem statement in JavaScript −

  • Using Regular Expression

  • Iteration Approach

Method 1: Using Regular Expression

To validate a password using regular expressions, create the function validatePassword, which takes a password as input. Define a regular expression pattern that enforces specific requirements for the password. Utilize the test method of the regular expression object to check if the password matches the pattern. If there is a match, return true to indicate a valid password; otherwise, return false.

Example

The validatePassword function takes a password as input and returns a boolean value indicating whether the password is valid or not.

The regular expression /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*()\-+.]).{6,20}$/ defines the pattern that the password must match.

  • (?=.*\d) asserts that the password must contain at least one digit.

  • (?=.*[a-z]) asserts that the password must contain at least one lowercase English character.

  • (?=.*[A-Z]) asserts that the password must contain at least one uppercase English character.

  • (?=.*[!@#$%^&*()\-+.]) asserts that the password must contain at least one special character from the specified set.

  • .{6,20} specifies that the password must be between 6 and 20 characters in length.

The test() method of the regular expression object is used to check if the password matches the defined pattern. It returns true if the password is valid, and false otherwise.

function validatePassword(password) {
   const regex = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*()\-+.]).{6,20}$/;
   return regex.test(password);
}
 
console.log(validatePassword("Abcdef123!"));
console.log(validatePassword("abc123"));

Output

The following is the console output −

true
false

Method 2: Iteration Approach

The character iteration approach utilizes a validatePassword function to check the validity of a given password. It verifies the password length and returns false if it's invalid. The function initializes boolean variables to track the presence of digits, lowercase and uppercase letters, and special characters in the password. It then iterates through each character, utilizing regular expressions and the includes method to verify if the requirements are met. The boolean variables are updated accordingly. If all requirements are satisfied, the function returns true; otherwise, if the loop completes without returning true, it indicates an invalid password, leading to a false return from the function.

Example

The validatePassword function checks if a password is valid by first verifying its length and returning false if it's too short or too long. It initializes boolean variables to track if the password has a digit, lowercase letter, uppercase letter, and special character. The function then iterates over each character, testing it against regular expressions to set the corresponding boolean variables. If all conditions are met, the function returns true; otherwise, it returns false to indicate an invalid password.

function validatePassword(password) {
   if (password.length < 6 || password.length > 20) {
      return false;
   }

   let hasDigit = false;
   let hasLowercase = false;
   let hasUppercase = false;
   let hasSpecialChar = false;
   const specialChars = "!@#$%^&*()-+.";

   for (let i = 0; i < password.length; i++) {
      const char = password[i];

      if (/[0-9]/.test(char)) {
         hasDigit = true;
      } else if (/[a-z]/.test(char)) {
         hasLowercase = true;
      } else if (/[A-Z]/.test(char)) {
         hasUppercase = true;
      } else if (specialChars.includes(char)) {
         hasSpecialChar = true;
      }

      if (hasDigit && hasLowercase && hasUppercase && hasSpecialChar) {
         return true;
      }
   }
   return false;
}
console.log(validatePassword("Abcdef123!")); 
console.log(validatePassword("abc123"));

Output

The following is the console output −

true
false

Conclusion

To conclude, the validation of a password using JavaScript can be an invaluable tool in fortifying the security of online platforms. By employing robust algorithms and implementing intricate validation rules, developers can ensure that users' passwords adhere to stringent criteria, minimizing the risk of unauthorized access. It is imperative to underscore that the efficacy of password validation hinges upon the judicious selection of uncommonly used word methods, which imbue the validation process with an added layer of sophistication. By integrating these techniques into web applications, developers can bolster user confidence, engendering a sense of trust and safeguarding sensitive information from malevolent actors. In essence, the meticulous validation of passwords using JavaScript represents a salient measure in augmenting the overall security posture of digital platforms.

Updated on: 04-Aug-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements