1

I'm trying to meet requirements from a client with a "New Password" solution.

I have this requirements:
1 - New password must be 8 - 13 characters,
2 - password must contain numbers,
3 - password must contain uppercase and lowercase,
4 - password must not contain username and finally
5 - password must not be used before.

I'm not an expert in Javascript and I have been trying to put all this requirements in a script, but i'm not sure how to solve the part 1,4,5 of this requirement, so i'm hoping someone can help me with what could I do in order to achieve all those requirements...

Also, my "Weak Password , Medium Password, Strong Password" message it's being showed at the top of a input element who was a ID called msg (just so you know)

Here is my script:

function validatePassword(password) {

  // Do not show anything when the length of password is zero.
  if (password.length === 0) {
    document.getElementById("msg").innerHTML = "";
    return;
  }

  // Create an array and push all possible values that you want in password

  var matchedCase = new Array();
  matchedCase.push("[$@$!%*#?&]"); // Special Charector
  matchedCase.push("[A-Z]"); // Uppercase Alpabates
  matchedCase.push("[0-9]"); // Numbers
  matchedCase.push("[a-z]"); // Lowercase Alphabates

  // Check the conditions
  var ctr = 0;
  for (var i = 0; i < matchedCase.length; i++) {
    if (new RegExp(matchedCase[i]).test(password)) {
      ctr++;
    }
  }
  // Display it
  var color = "";
  var strength = "";
  switch (ctr) {
    case 0:
    case 1:
    case 2:
          strength = "Contraseña Débil";
          color = "red";
          break;
    case 3:
          strength = "Contraseña Regular";
          color = "orange";
          break;
    case 4:
          strength = "Contraseña Fuerte";
          color = "green";
          break;
  }
  document.getElementById("msg").innerHTML = strength;
  document.getElementById("msg").style.color = color;
}
6
  • You can't implement #5 in the client. The server has to save all the old passwords, and then you use AJAX to query the server.
    – Barmar
    Oct 10, 2019 at 21:41
  • Part 5 cannot be validated client-side, and must be done server-side. You'll have to make an AJAX request to the back-end, and then check the response. Oct 10, 2019 at 21:41
  • #1 is the easiest thing to test. What problem are you having with it?
    – Barmar
    Oct 10, 2019 at 21:41
  • @Barmar I was wondering if #5 was server or client side, so we can forget about #5 (since theres a IT team that manage the server side of things) What I can't implement in my script it's #1 and #4 , and i'm not sure if #2 & #3 are correct Oct 10, 2019 at 21:44
  • What part of #1 are you having trouble with? Do you know how to get the length of a string? Do you know how to compare numbers? If you know how to do each of those things, just put them together.
    – Barmar
    Oct 10, 2019 at 21:46

3 Answers 3

0

1.- Handle password length (range between 8-13)

I would suggest that, for the max length, you use the native attribute for inputs maxlength:

<input maxlength="13">

And update your function to not show anything about password strength until length is bigger than 8:

if (password.length < 8) {
  document.getElementById("msg").innerHTML = "";
  return;
}

2 and 3 works correctly, well done.


4.- Password must not contain username

Understanding you have saved the username somewhere else accesible by the scope, you can simply add another if below where you evaluate password length doing a return in case password contains username:

if (password.includes(username)) {
    document.getElementById("msg").innerHTML = "La contraseña no debe contener el nombre de usuario.";
    return;
}

The message is up to you, just placed something demostrative.


5.- Is out, this MUST be handled server-side.


And finally, look at the final code:

const username = "k3llydev";

function validatePassword(password) {

  // Do not show anything when the length of password is zero.
  if (password.length < 8) {
    document.getElementById("msg").innerHTML = "";
    return;
  }
  
  if (password.includes(username)) {
    document.getElementById("msg").innerHTML = "La contraseña no debe contener el nombre de usuario.";
    return;
  }

  // Create an array and push all possible values that you want in password

  var matchedCase = new Array();
  matchedCase.push("[$@$!%*#?&]"); // Special Charector
  matchedCase.push("[A-Z]"); // Uppercase Alpabates
  matchedCase.push("[0-9]"); // Numbers
  matchedCase.push("[a-z]"); // Lowercase Alphabates

  // Check the conditions
  var ctr = 0;
  for (var i = 0; i < matchedCase.length; i++) {
    if (new RegExp(matchedCase[i]).test(password)) {
      ctr++;
    }
  }
  // Display it
  var color = "";
  var strength = "";
  switch (ctr) {
    case 0:
    case 1:
    case 2:
      strength = "Contraseña Débil";
      color = "red";
      break;
    case 3:
      strength = "Contraseña Regular";
      color = "orange";
      break;
    case 4:
      strength = "Contraseña Fuerte";
      color = "green";
      break;
  }
  document.getElementById("msg").innerHTML = strength;
  document.getElementById("msg").style.color = color;
}
<input onkeyup="validatePassword(this.value)" maxlength="13">
<span id="msg"></span>

5
  • I really appreciate your detailed answer, but I was wondering...how do I know if they can't send the password unless it's minimum 8 characters? or they will be avaible of send the password eventhought they do not meet the requisite of minimun 8? Also, there's another way on showing the "msg" even we they haven't type the 8 characters? Oct 10, 2019 at 22:09
  • @FernandoSoto Always glad to help. I am thinking you are handling this with JavaScript and you just showed specifically what you need to do, ain't you validating this already? About showing the message even when the password length is not met, you can separate if conditionals (you can tell me if you still not understand to edit my answer)
    – k3llydev
    Oct 10, 2019 at 22:20
  • @MisterJojo and is that a requirement by the user?
    – k3llydev
    Oct 10, 2019 at 22:23
  • @k3llydev I'm sorry I don't understand what do you mean with the conditional, would be too much to ask if you show me what are you saying? Oct 10, 2019 at 22:26
  • Yes it is a requirement by the user ! or explain me why Ñ or ñ should be not uppercase and lowercase characters Oct 10, 2019 at 22:28
0

First of all I wouldn't recommend validating passwords client side. It can be easily manipulated and isn't secure. Validating passwords server side is the way to go. You said you have people doing server side stuff already, they should be the ones that are validating any information (including passwords) before putting it into some sort of database.

But since that doesn't answer your question:

Part 5 cannot be client side. You would have to check with the server to validate the old password.

Part 1 is simple, you already know how to find the password length as you have that in your code

if(password.length >= 8 && password.length <= 13) {
    //length is valid
}

As for part 4, you would need to have their username which I don't see anywhere in your code, so ill just create a random variable for it.

var username = "example";
if(password.indexOf(username)) > -1) {
    // password contains username
{
1
  • Thank you for your help, just have a question, length valid part, should be inside the //check condition part? Oct 10, 2019 at 21:57
0

3 - password must contain uppercase and lowercase,

Your actual test 3 is wrong, because it does not consider diacritic signs. A correct test is:

const username = "k3llydev";


function validatePassword(psw)
{
  let msg = 'password is OK (for 1,2,3,4)'

  switch (true) {
  case  (psw.length < 8 || psw.length > 13):
    msg = '1) bad password length'
    break
  case  (!(/[0-9]/.test(psw))):
    msg = '2) password must contain numbers'
    break
  case (psw == psw.toLowerCase()) || (psw == psw.toUpperCase()):
    msg = '3) password must contain UPPER and lower characters'
    break
  case ( psw.includes(username)):
    msg = '4) password must not contain username'
    break
  }
  return msg
}



console.log ('abc              -> ', validatePassword('abc') )
console.log ('abcdefghijklmnop -> ', validatePassword('abcdefghijklmnop') )
console.log ('CONTRASEÑA       -> ', validatePassword('CONTRASEÑA') )
console.log ('CONT123RASEÑA    -> ', validatePassword('CONT123RASEÑA') )
console.log ('cont123raseña    -> ', validatePassword('cont123raseña') )
console.log ('C1ak3llydevÑ     -> ', validatePassword('C1ak3llydevÑ') )
console.log ('cont123raseÑa    -> ', validatePassword('cont123raseÑa') )
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {min-height:100% !important; top:0;}

2
  • But how does I can put this test right in my script? Oct 10, 2019 at 22:40
  • @FernandoCarvajal :Well I have just changing my answer to show code validation for 1 to 4 points Oct 10, 2019 at 23:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.