Validate password with Regex

Asked

Viewed 72 times

0

I’m trying to do an exercise where I need to validate a password, I tried this format but the conditional if seems to ignore the second condition. I could not find the problem, which may be?

{
        let senha = 'Guilhe3rme';
        const regex = /[0-9]/;


         if((senha.length > 5 && senha.length < 10) && (regex.test(senha) == true)){  
               console.log("Senha válida!")
         }else{
               console.log("Senha inválida!");
         }
}

In the console only the "Invalid password!" comes out, if I remove the second condition the console displays the "Valid password!"

In the exercise the password must be between 5 and 10 characters long and contain at least one digit of 0-9.

  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).

1 answer

7

Guilhe3rme has 10 letters, the second condition requires you to have less than 10 To be true, therefore, the second is false. As it is connected with others with && which requires all conditions to be true to give true end result, then it will fall into the else.

Note that the operator < means it has to be smaller than that, that number does not enter. If your intention was to be up to 10, then you should use <= 10 or < 11. Just as the first condition requires a minimum of 6 characters and not 5 as you may be thinking.

Then there was an edition in the question that makes this clearer, then, in my interpretation, since the statement is ambiguous and does not say whether it is inclusive or exclusive, and if it is on both sides, it really seems that the condition should be:

if (senha.length >= 5 && senha.length <= 10 && regex.test(senha)) {

I haven’t checked the Regex is correct.

  • That’s right, thank you very much!

  • I have my doubts, anyway take a look at the [tour] the best way to say thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.