Reputation: 123
I'm writing some JavaScript code as part of my homework to create a password generator app and I have decided to put all the questions that I should ask from the user inside a function. One of the criteria to generate a password is to choose the number of characters between 8 and 128. I wanted to be sure that the user enters the correct number otherwise the function restarts and won't let the user see the rest of the confirm boxes until he enters the desired number so I wrote it like this:
function askQuestions() {
let numOfChracaters = +prompt("Choose the number of characters for your password (between 8 and 128)");
console.log(numOfChracaters);
if (numOfChracaters >= 8 || numOfChracaters <= 128) {
let hasUppercase = confirm("Do you want your password to include uppercase letters?");
let hasLowercase = confirm("Do you want your password to include lowercase letters?");
let hasNumber = confirm("Do you want your password to include numbers?");
let hasSpecialCharacters = confirm("Do you want your password to include special characters?");
let prefrencesArray = [numOfChracaters, hasUppercase, hasLowercase, hasNumber, hasSpecialCharacters];
return prefrencesArray;
} else {
askQuestions();
}
}
But for some reason it doesn't work and still allows user to enter whatever number they want. Any ideas what did I do wrong here?
Upvotes: 0
Views: 45
Reputation: 690
if (numOfChracaters >= 8 && numOfChracaters <= 128)
Since for your OR (||
) operator, it was true for the condition numOfChracaters <= 128, thus according to you inputs
(false || true)=> returns true. and (false && true)=> return false
Explaining your mistake so that next time you don't make such error.
Upvotes: 0
Reputation: 22683
You have made a funny mistake. Every number is either >= 8 OR <= 128.
What you're looking for is &&
operator, because both sides need to be true at the same time.
Upvotes: 1
Reputation: 581
You can use an infinite loop to run till the requirements are met
let numOfChracaters = 0;
while(numOfChracaters < 8) {
numOfChracaters = +prompt("Choose the number of characters for your password (between 8 and 128)");
}
Upvotes: 0
Reputation: 164
replace conditional
numOfChracaters >= 8 || numOfChracaters <= 128
to
numOfChracaters >= 8 && numOfChracaters <= 128
Upvotes: 1