DEV Community

Cover image for JS: How to Check if a password is valid and make your site more secure

JS: How to Check if a password is valid and make your site more secure

devlorenzo profile image DevLorenzo ・Updated on ・2 min read

Hello World! The height episode of the series - A CSS/JS trick in 5 minutes.
My first ever article was about HTML forms, in the last part, I explained you how to check if a password is valid. I will do the same here while going a little bit deeper.

We can have a lot of different types of password blockers. From the narrowest to the freest.

We first can just have a length validator:

function CheckPasswordLength (password) {
  if(password.length < 8 or password.length > 16) {   
     return false;  
  }  else {
     return true;
Enter fullscreen mode Exit fullscreen mode

Then we can use regex for a more advanced test:

function checkPassword (password) { 
  var paswd =  /^(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{8,16}$/;
  if(password.value.match(paswd)) { 
   return true;
  } else { 
   return false;
Enter fullscreen mode Exit fullscreen mode

This condition will check for numbers, special characters, uppercase, lowercase and length.

if you don't know how regex work, check this:

A JavaScript Regular Expression (or Regex) is a sequence of characters that we can utilize to work effectively with strings. Using this syntax, we can search for text in a string, replace substrings in a string or extract information from a string.
Check this article to learn more about regex.

I also highly recommend you to add a code to check that the two passwords inserted are the same:

function checkMatching(password, confirmationPassword) {
  if (password.value === confirmationPassword.value) {
    return true
  } else {
    return false
Enter fullscreen mode Exit fullscreen mode

If you need it I also did an article on how to check if an email is valid.

Hope this helped and thanks for reading!

Please smash that like button to make me understand that you want the series to continue :)

Check this article about how to write CSS like a pro!

Discussion (1)

Editor guide
darkain profile image
Vincent Milum Jr

Please do NOT set a 16 character maximum. Password managers will generate strong entropy random passwords, and devices like a Yubikey can also supply a 32+ character password.

And honestly, the upper/lower/number/symbol is based on old knowledge that really isn't great anymore. The test should be for entropy instead of a set regex. By limiting to 16 characters, you're hurting potential random entropy from the input, essentially limiting the possibilities of stronger hashing algorithms that exist today.

Security, especially around passwords, is a topic that should be peer reviewed by experts in the field, no single person should be coming up with the spec or implementation. This is exactly how all of these large scale exploits are happening.