Emerging TechnologyCRM and Data PlatformsEmail Marketing & Email Marketing Automation

Check Password Strength with JavaScript and Regular Expressions (With Server-Side Examples, Too!)

I was doing some research on finding a good example of a Password Strength checker that uses JavaScript and Regular Expressions (Regex). In the application at my work, we do a post back to verify the password strength and it’s quite inconvenient for our users.

What is Regex?

A regular expression is a sequence of characters that define a search pattern. Usually, such patterns are used by string searching algorithms for find or find and replace operations on strings, or for input validation. 

This article is definitely not to teach you regular expressions. Just know that the ability to use Regular Expressions will absolutely simplify your development as you search for patterns in text. It’s also important to note that most development languages have optimized regular expression use… so rather than parsing and searching strings step-by-step, Regex is typically much faster both server and client-side.

I searched the web quite a bit before I found an example of some great Regular Expressions that look for a combination of length, characters, and symbols. Howver, the code was a little excessive for my taste and tailored for .NET. So I simplified the code and put it in JavaScript. This makes it validate the password strength in real-time on the client’s browser before posting it back… and provides some feedback to the user on the password’s strength.

Type A Password

With each stroke of the keyboard, the password is tested against the regular expression and then feedback is provided to the user in a span beneath it.

Here’s the Code

The Regular Expressions do a fantastic job of minimizing the length of the code. This Javascript function checks the strength of a password and whether foiling it is easy, medium, difficult, or extremely difficult to guess. As the person types, it displays tips on encouraging it to be stronger. It validates the password based on:

  • Length – If the length is under or over 8 characters.
  • Mixed Case – If the password has both upper and lower case characters.
  • Numbers – If the password includes numbers.
  • Special Characters – If the password includes special characters.

The function displays the difficulty as well as some tips on hardening the password further.

function checkPasswordStrength(password) {
  // Initialize variables
  var strength = 0;
  var tips = "";

  // Check password length
  if (password.length < 8) {
    tips += "Make the password longer. ";
  } else {
    strength += 1;
  }

  // Check for mixed case
  if (password.match(/[a-z]/) && password.match(/[A-Z]/)) {
    strength += 1;
  } else {
    tips += "Use both lowercase and uppercase letters. ";
  }

  // Check for numbers
  if (password.match(/\d/)) {
    strength += 1;
  } else {
    tips += "Include at least one number. ";
  }

  // Check for special characters
  if (password.match(/[^a-zA-Z\d]/)) {
    strength += 1;
  } else {
    tips += "Include at least one special character. ";
  }

  // Return results
  if (strength < 2) {
    return "Easy to guess. " + tips;
  } else if (strength === 2) {
    return "Medium difficulty. " + tips;
  } else if (strength === 3) {
    return "Difficult. " + tips;
  } else {
    return "Extremely difficult. " + tips;
  }
}

Hardening Your Password Request

It’s essential that you don’t just validate the password construction within your Javascript. This would enable anyone with browser development tools to bypass the script and use whatever password they’d like. You should ALWAYS utilize a server-side check to validate the password strength before storing it in your platform.

PHP Function For Password Strength

function checkPasswordStrength($password) {
  // Initialize variables
  $strength = 0;

  // Check password length
  if (strlen($password) < 8) {
    return "Easy to guess";
  } else {
    $strength += 1;
  }

  // Check for mixed case
  if (preg_match("/[a-z]/", $password) && preg_match("/[A-Z]/", $password)) {
    $strength += 1;
  }

  // Check for numbers
  if (preg_match("/\d/", $password)) {
    $strength += 1;
  }

  // Check for special characters
  if (preg_match("/[^a-zA-Z\d]/", $password)) {
    $strength += 1;
  }

  // Return strength level
  if ($strength < 2) {
    return "Easy to guess";
  } else if ($strength === 2) {
    return "Medium difficulty";
  } else if ($strength === 3) {
    return "Difficult";
  } else {
    return "Extremely difficult";
  }
}

Python Function For Password Strength

def check_password_strength(password):
  # Initialize variables
  strength = 0

  # Check password length
  if len(password) < 8:
    return "Easy to guess"
  else:
    strength += 1

  # Check for mixed case
  if any(char.islower() for char in password) and any(char.isupper() for char in password):
    strength += 1

  # Check for numbers
  if any(char.isdigit() for char in password):
    strength += 1

  # Check for special characters
  if any(not char.isalnum() for char in password):
    strength += 1

  # Return strength level
  if strength < 2:
    return "Easy to guess"
  elif strength == 2:
    return "Medium difficulty"
  elif strength == 3:
    return "Difficult"
  else:
    return "Extremely difficult"

C# Function For Password Strength

public string CheckPasswordStrength(string password) {
  // Initialize variables
  int strength = 0;

  // Check password length
  if (password.Length < 8) {
    return "Easy to guess";
  } else {
    strength += 1;
  }

  // Check for mixed case
  if (password.Any(char.IsLower) && password.Any(char.IsUpper)) {
    strength += 1;
  }

  // Check for numbers
  if (password.Any(char.IsDigit)) {
    strength += 1;
  }

  // Check for special characters
  if (password.Any(ch => !char.IsLetterOrDigit(ch))) {
    strength += 1;
  }

  // Return strength level
  if (strength < 2) {
    return "Easy to guess";
  } else if (strength == 2) {
    return "Medium difficulty";
  } else if (strength == 3) {
    return "Difficult";
  } else {
    return "Extremely difficult";
  }
}

Java Function For Password Strength

public String checkPasswordStrength(String password) {
  // Initialize variables
  int strength = 0;

  // Check password length
  if (password.length() < 8) {
    return "Easy to guess";
  } else {
    strength += 1;
  }

  // Check for mixed case
  if (password.matches(".*[a-z].*") && password.matches(".*[A-Z].*")) {
    strength += 1;
  }

  // Check for numbers
  if (password.matches(".*\\d.*")) {
    strength += 1;
  }

  // Check for special characters
  if (password.matches(".*[^a-zA-Z\\d].*")) {
    strength += 1;
  }

  // Return strength level
  if (strength < 2) {
    return "Easy to guess";
  } else if (strength == 2) {
    return "Medium difficulty";
  } else if (strength == 3) {
    return "Difficult";
  } else {
    return "Extremely difficult";
  }
}

Douglas Karr

Douglas Karr is the founder of the Martech Zone and a recognized expert on digital transformation. Douglas has helped start several successful MarTech startups, has assisted in the due diligence of over $5 bil in Martech acquisitions and investments, and continues to launch his own platforms and services. He's a co-founder of Highbridge, a digital transformation consulting firm. Douglas is also a published author of a Dummie's guide and a business leadership book.

Related Articles

33 Comments

  1. THANK YOU! THANK YOU! THANK YOU! I’ve been fooling around for 2 weeks with damn password strength code from other websites and pulling my hair out. Yours is short, works just like I want and best of all, easy for a javascript novice to modify! I wanted to capture the strength verdict and not let the form post to actually update the user’s password unless it met the strength test. Other people’s code was too complicated or didn’t work right or something else. I love you! XXXXX

  2. Hi,first of all thanks alot for ur efforts,I tried to use this with Asp.net but didn’t work,i’m using

    instead of tag,and it didn’t work,any suggestions?!

  3. “P@s$w0rD” shows at strong, although it would be cracked fairly quickly with a dictionnary attack…
    To deploy such a feature on a professionnal solution, I believe it is important to combine this algorithm with a dictionnary check.

  4. can somebody tell, why it did not work mine..

    i copied all the code, and paste it to notepad++ , but it does not work at all ?
    please help me..

  5. This type of “strength checker” leads people down a very dangerous path. It values character diversity over passphrase length, leading it to rate shorter, more diverse passwords as stronger than longer, less diverse passwords. That is a fallacy that will get your users into trouble if they ever face a serious hacking threat.

    1. I don’t disagree, Jordan! The example was simply put out as an example of the script. My recommendation for people is to utilize a password management tool to create independent passphrases for any site that are unique to it. Thanks!

  6. You are a live saver! I was parsing strings left right and centre and thought there is a better way and found your piece of code using Regex. Was able to tinkle with it for my site…You have no idea how much this helped. Thanks so much Douglas!!

What do you think?

This site uses Akismet to reduce spam. Learn how your comment data is processed.