Need help clearing text area after JavaScript function is ran again - javascript

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Password Generator</title>
<link rel="stylesheet" href="assets\css\style.css" />
</head>
<body>
<div class="wrapper">
<!-- || HEADER || -->
<header>
<h1>Password Generator</h1>
</header>
<!-- || CONTENT || -->
<div class="card">
<div class="card-header">
<h2>Generate a Password</h2>
</div>
<div class="card-body">
<textarea readonly id="password" placeholder="Your Secure Password" aria-label="Generated Password"></textarea>
</div>
<div class="card-footer">
<button id="generate" class="btn">Generate Password</button>
<button id="copy" class="btn-copy">Copy to Clipboard</button>
</div>
</div>
</div>
<!-- || JAVASCRIPT STYLE SHEET || -->
<script src="assets\js\script.js"></script>
</body>
</html>
---- || JavaScript || ----
// GenerateBtn
var generateBtn = document.querySelector("#generate");
// Define variables
var selectLowerCase;
var selectUpperCase;
var selectNumber;
var selectSpecial;
// Set variables
var plength = 0;
var lowerCase = "abcdefghijklmnopqrstuvwxyz";
// Uppercase conversion
var upperCase = lowerCase.toUpperCase();
var numbers = "1234567890";
var specialCharacter = "!#$%&'()*+,-./:;?#][^_`{|}~'<=>";
var userPassword = "";
var passwordGroup = "";
// Function writes password to the #password input
function writePassword() {
var password = generatePassword();
var passwordText = document.querySelector("#password");
passwordText.value = password;
}
// Clicking btn runs funtion
generateBtn.addEventListener("click", writePassword);
// Request length of the password
var plength = parseInt(prompt("Welcome to Password Generator 2020. To begin, please enter a length of your password from 8-128.",""));
// Require number
while (isNaN(plength)) {
var plength = parseInt(prompt("This is not a number. Please enter a number between 8 - 128.",""));
}
// Require length
while (plength < 8 || plength > 128) {
var plength = parseInt(prompt("Enter length of password.* Length must be between 8 - 128 characters",""));
}
// Confirm lower case letters
var selectLowerCase = confirm("Use lower case letters?");
// Confirm upper case letters
var selectUpperCase = confirm("Use upper case letters?");
//Confirm numeric characters
var selectNumber = confirm("Use numbers?");
//Confirm special characters
var selectSpecial = confirm("Use special characters?");
// Call function to generate password
generatePassword();
// Write generated password on page
document.getElementById("password").innerHTML = userPassword;
// From selected options randomly generate password.
function generatePassword() {
if (selectLowerCase) {
passwordGroup += lowerCase;
}
if (selectUpperCase) {
passwordGroup += upperCase;
}
if (selectNumber) {
passwordGroup += numbers;
}
if (selectSpecial) {
passwordGroup += specialCharacter;
}
for (let i = 0; i < plength; i++) {
userPassword += passwordGroup.charAt(
Math.floor(Math.random() * passwordGroup.length)
);
}
return userPassword;
}
/* || COPY FUNCTION || */
// https://www.w3schools.com/howto/howto_js_copy_clipboard.asp
var copy = document.querySelector("#copy");
copy.addEventListener("click", function () {
copyPassword();
});
function copyPassword() {
document.getElementById("password").select();
document.execCommand("Copy");
alert("Password copied to clipboard!");
}
What I want it to do is wait to run the prompts till after the page loads and you click the generate button. Then when clicking the generate button again I want it to clear the text area and repeat the prompts. Currently, it's asking the prompts when the page loads then running the function again with the same prompts originally chosen and adding them to the text previously in the text area.

In order to display the pop-up only when the button "Generate Password" is clicked, you should insert all the pop-ups in the writePassword function:
function writePassword() {
// Request length of the password
plength = parseInt(prompt("Welcome to Password Generator 2020. To begin, please enter a length of your password from 8-128.", ""));
// Require number
while (isNaN(plength)) {
plength = parseInt(prompt("This is not a number. Please enter a number between 8 - 128.", ""));
}
// Require length
while (plength < 8 || plength > 128) {
plength = parseInt(prompt("Enter length of password.* Length must be between 8 - 128 characters", ""));
}
// Confirm lower case letters
selectLowerCase = confirm("Use lower case letters?");
// Confirm upper case letters
selectUpperCase = confirm("Use upper case letters?");
//Confirm numeric characters
selectNumber = confirm("Use numbers?");
//Confirm special characters
selectSpecial = confirm("Use special characters?");
var password = generatePassword();
document.querySelector("#password").value = password;
}
Then, in order to clear the password area you should simply set the userPassword variable to a null string before you start generating a new password (since you append the random generated characters):
function generatePassword() {
userPassword = "";
if (selectLowerCase) {
passwordGroup += lowerCase;
}
if (selectUpperCase) {
passwordGroup += upperCase;
}
if (selectNumber) {
passwordGroup += numbers;
}
if (selectSpecial) {
passwordGroup += specialCharacter;
}
for (let i = 0; i < plength; i++) {
userPassword += passwordGroup.charAt(
Math.floor(Math.random() * passwordGroup.length)
);
}
return userPassword;
}
This is the complete JavaScript code:
// GenerateBtn
var generateBtn = document.querySelector("#generate");
// Define variables
var selectLowerCase;
var selectUpperCase;
var selectNumber;
var selectSpecial;
// Set variables
var plength = 0;
var lowerCase = "abcdefghijklmnopqrstuvwxyz";
// Uppercase conversion
var upperCase = lowerCase.toUpperCase();
var numbers = "1234567890";
var specialCharacter = "!#$%&'()*+,-./:;?#][^_`{|}~'<=>";
var userPassword = "";
var passwordGroup = "";
var plength;
var selectLowerCase;
var selectUpperCase;
var selectNumber;
var selectSpecial;
// Function writes password to the #password input
function writePassword() {
// Request length of the password
plength = parseInt(prompt("Welcome to Password Generator 2020. To begin, please enter a length of your password from 8-128.", ""));
// Require number
while (isNaN(plength)) {
plength = parseInt(prompt("This is not a number. Please enter a number between 8 - 128.", ""));
}
// Require length
while (plength < 8 || plength > 128) {
plength = parseInt(prompt("Enter length of password.* Length must be between 8 - 128 characters", ""));
}
// Confirm lower case letters
selectLowerCase = confirm("Use lower case letters?");
// Confirm upper case letters
selectUpperCase = confirm("Use upper case letters?");
//Confirm numeric characters
selectNumber = confirm("Use numbers?");
//Confirm special characters
selectSpecial = confirm("Use special characters?");
var password = generatePassword();
document.querySelector("#password").value = password;
}
// Clicking btn runs funtion
generate.addEventListener("click", writePassword);
// Call function to generate password
generatePassword();
// Write generated password on page
document.getElementById("password").innerHTML = userPassword;
// From selected options randomly generate password.
function generatePassword() {
userPassword = "";
if (selectLowerCase) {
passwordGroup += lowerCase;
}
if (selectUpperCase) {
passwordGroup += upperCase;
}
if (selectNumber) {
passwordGroup += numbers;
}
if (selectSpecial) {
passwordGroup += specialCharacter;
}
for (let i = 0; i < plength; i++) {
userPassword += passwordGroup.charAt(
Math.floor(Math.random() * passwordGroup.length)
);
}
return userPassword;
}
/* || COPY FUNCTION || */
// https://www.w3schools.com/howto/howto_js_copy_clipboard.asp
var copy = document.querySelector("#copy");
copy.addEventListener("click", function() {
copyPassword();
});
function copyPassword() {
document.getElementById("password").select();
document.execCommand("Copy");
alert("Password copied to clipboard!");
}

Try refactoring your code
Make a separate function for all your prompts.
Call the function when the DOM is completely loaded.
And at the starting of the function always set the value of your password textarea to empty.

Related

Why isn't my JS code working? I'm trying to get this code to generate a random password

EDIT: Made some changes, now when I click generate password, I get back 'undefined'. Progress!
EDIT #2: Now I am not getting 'undefined' when I click, but devtools says at line 26 i am exceeding maximum call stack. How do I fix that?
Javascript is really hard, man. I'm trying to get this code to generate a random password. When I click the generate password button, nothing happens. Chrome dev tools doesn't show any issues. I just started learning javascript a week ago. I need to add more details to post this so...I think I just threw in everything I 'learned' in here, so it's probably really messed up.
// Assignment code here
var length;
var number;
var specialCharacter;
var upperCase;
var lowåerCase;
var selection;
var lettersUp
const characters = ["number", "letters", "character"];
number = "0123456789";
letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
character = "!##$%^&*)(";
// Get references to the #generate element
var generateBtn = document.querySelector("#generate");
// Write password to the #password input
function writePassword() {
var password = generatePassword();
var passwordText = document.querySelector("#password");
passwordText.value = password;
}
// Begin setting password parameters
function generatePassword() {
document.getElementById("click", generatePassword); {
for ( let i = 0; i < length; i++ ) {
console.log(password);
}
}
// Select # of characters for new password
length = prompt("Enter the number of characters you'd like for your new password (Select a number between 8-128)");
if (!length) {
alert("Please make a valid entry");
} else if (length < 8 || length > 128) {
// Function recognizes incorrect input
length = prompt("New password must be from 8-128 characters");
} else {
// Prompts continue when length input is valid
number = confirm("Include numbers in your new password?");
specialCharacter = confirm("Include special characters in your new password?");
upperCase = confirm("Include uppercase letters?");
lowerCase = confirm("Include lowercase letters?");
};
// for all of the above true
if (number && specialCharacter && upperCase && lowerCase) {
selection = character.concat(number,letters,lettersUp);
}
// three options selected
else if (number && specialCharacter && upperCase) {
selection = character.concat(number, lettersUp);
}
else if (specialCharacter && upperCase && lowerCase) {
selection = character.concat(letters, lettersUp);
}
else if (upperCase && lowerCase && number) {
selection = lettersUp.concat(letters, number);
}
else if (lowerCase && number && specialCharacter) {
selection = letters.concat(number, character);
}
//two options selected
else if (specialCharacter && number) {
selection = character.concat(number);
}
else if (number && upperCase) {
selection = number.concat(lettersUp);
}
else if (upperCase && lowerCase) {
selection = lettersUp.concat(letters);
}
else if (lowerCase && number) {
selection = letters.concat(number);
}
else if (lowerCase && specialCharacter) {
selection = letters.concat(character);
}
else if (specialCharacter && upperCase) {
selection = character.concat(lettersUp);
}
//one option
else if (specialCharacter) {
selection = character;
}
else if (number) {
selection = number;
}
else if (lowerCase) {
selection = letters;
}
else if (upperCase) {
selection = lettersUp;
};
}
generatePassword();
// Add event listener to generate button
generateBtn.addEventListener("click", writePassword);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Password Generator</title>
<link rel="stylesheet" href="./assets/css/style.css" />
</head>
<body>
<div class="wrapper">
<header>
<h1>Password Generator</h1>
</header>
<div class="card">
<div class="card-header">
<h2>Generate a Password</h2>
</div>
<div class="card-body">
<textarea
readonly
id="password"
placeholder="Your Secure Password"
aria-label="Generated Password"
></textarea>
</div>
<div class="card-footer">
<button id="generate" class="btn">Generate Password</button>
</div>
</div>
</div>
<script src="./assets/js/script.js"></script>
</body>
</html>
You forgot to return in generatePassword(). Also I guess you forgot to initialize lettersUp. I fixed that for you. Maybe you want to shuffle the string and use substr to extract only a substring with a certain length afterward. Also as a reminder, there is a strange character in your lowerCase variable originally. Double-check if that is intended.
// Assignment code here
var length;
var number;
var specialCharacter;
var upperCase;
var lowerCase;
var selection;
var lettersUp
const characters = ["number", "letters", "character"];
number = "0123456789";
letters = "abcdefghijklmnopqrstuvwxyz";
lettersUp = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
character = "!##$%^&*)()";
// Get references to the #generate element
var generateBtn = document.querySelector("#generate");
// Write password to the #password input
function writePassword() {
var password = generatePassword();
var passwordText = document.querySelector("#password");
passwordText.value = password;
}
// Begin setting password parameters
function generatePassword() {
// Select # of characters for new password
length = prompt("Enter the number of characters you'd like for your new password (Select a number between 8-128)");
if (!length) {
alert("Please make a valid entry");
} else if (length < 8 || length > 128) {
// Function recognizes incorrect input
length = prompt("New password must be from 8-128 characters");
} else {
// Prompts continue when length input is valid
number = confirm("Include numbers in your new password?");
specialCharacter = confirm("Include special characters in your new password?");
upperCase = confirm("Include uppercase letters?");
lowerCase = confirm("Include lowercase letters?");
};
// for all of the above true
if (number && specialCharacter && upperCase && lowerCase) {
selection = character.concat(number, letters, lettersUp);
}
// three options selected
else if (number && specialCharacter && upperCase) {
selection = character.concat(number, lettersUp);
} else if (specialCharacter && upperCase && lowerCase) {
selection = character.concat(letters, lettersUp);
} else if (upperCase && lowerCase && number) {
selection = lettersUp.concat(letters, number);
} else if (lowerCase && number && specialCharacter) {
selection = letters.concat(number, character);
}
//two options selected
else if (specialCharacter && number) {
selection = character.concat(number);
} else if (number && upperCase) {
selection = number.concat(lettersUp);
} else if (upperCase && lowerCase) {
selection = lettersUp.concat(letters);
} else if (lowerCase && number) {
selection = letters.concat(number);
} else if (lowerCase && specialCharacter) {
selection = letters.concat(character);
} else if (specialCharacter && upperCase) {
selection = character.concat(lettersUp);
}
//one option
else if (specialCharacter) {
selection = character;
} else if (number) {
selection = number;
} else if (lowerCase) {
selection = letters;
} else if (upperCase) {
selection = lettersUp;
};
return selection;
}
// Add event listener to generate button
generateBtn.addEventListener("click", writePassword);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Password Generator</title>
<link rel="stylesheet" href="./assets/css/style.css" />
</head>
<body>
<div class="wrapper">
<header>
<h1>Password Generator</h1>
</header>
<div class="card">
<div class="card-header">
<h2>Generate a Password</h2>
</div>
<div class="card-body">
<textarea
readonly
id="password"
placeholder="Your Secure Password"
aria-label="Generated Password"
></textarea>
</div>
<div class="card-footer">
<button id="generate" class="btn">Generate Password</button>
</div>
</div>
</div>
<script src="./assets/js/script.js"></script>
</body>
</html>

Javascript password validation with regular expression

im trying to validate a password field with the following conditions, if the requirements are meet the password field should change its color to green if not should be red:
One lowercase character
One uppercase character
One number
One special character
Eight characters minimum
i tried with a regular expression but somehow it only makes it red even if i input a password with all the requirements. Any idea?
let passwordField = document.getElementById("password");
passwordField.addEventListener("focusout", () => {
let checkPass =
/^(?=.*[a-z])(?=.*[A-Z])(?=.*d)(?=.*[#$!%*?&])[A-Za-zd#$!%*?&]{8,}$/;
if (checkPass.test(password.value)) {
passwordField.style.backgroundColor = "green";
console.log("green");
} else {
passwordField.style.backgroundColor = "red";
console.log("red");
}
});
RegEx should be:
^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!##\$%\^&\*])(?=.{8,})
Where:
lower char = (?=.*[a-z])
upper char = (?=.*[A-Z])
1 number = (?=.*[0-9])
special char = (?=.*[!##\$%\^&\*])
min length to 8 = (?=.{8,})
let passwordField = document.getElementById("password");
passwordField.addEventListener("focusout", () => {
let checkPass =
new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!##\$%\^&\*])(?=.{8,})");
if (checkPass.test(password.value)) {
passwordField.style.backgroundColor = "green";
console.log("green");
} else {
passwordField.style.backgroundColor = "red";
console.log("red");
}
});
<input id="password" />
And the result is:
Please check this, it is exact same you want
let passwordField = document.getElementById("password");
passwordField.addEventListener("focusout", () => {
var decimal= /^(?=.*\d)(?=.*[!##$%^&*])(?=.*[a-z])(?=.*[A-Z]).{8,}$/;
if (passwordField.value.match(decimal)) {
passwordField.style.backgroundColor = "green";
console.log("green");
} else {
passwordField.style.backgroundColor = "red";
console.log("red");
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<title>Password</title>
</head>
<body>
<h1>This is a password validation</h1>
<input id="password" />
</body>
</html>

Random password generator javascript not returning password

I'm new to coding and I can't figure out why my JS isn't generating a random password. Click ok through the prompts and you will see the issue I am having. It appears to just be pulling one of my functions in //Generator Functions. I coded the prompts to be very simple since I still don't quite know what I'm doing. I just need it to generate the password for this particular exercise. Any help is appreciated!
// Assignment Code
var generateBtn = document.querySelector("#generate");
// Special characters for the function created
const specialCharacters = "!##$%^&*()";
// Write password to the #password input
function writePassword() {
var password = generatePassword();
var passwordText = document.querySelector("#password");
passwordText.value = password;
}
// Add event listener to generate button
generateBtn.addEventListener("click", writePassword);
// Prompts that come up after you click generate password
function generatePassword() {
var passwordLength = prompt("Please enter the number of characters you want for you new password. It must be more than 12 but less than 128.");
var numbers = confirm("Do you want numbers in your password?");
var lowerCases = confirm("Do you want lowercases in your password?");
var upperCases = confirm("Do you want uppercases in your password?");
var special = confirm("Do you want special characters in your password?");
// this is a minimum count for numbers, lowerCases, upperCases & specialCharacters
var minimumCount = 0;
// Empty minimums for numbers, lowerCases, upperCases & specialCharacters
var minimumNumbers = "";
var minimumLowerCases = "";
var minimumUpperCases = "";
var minimumSpecialCharacters = "";
**// Generator functions**
var functionArray = [
function getNumbers() {
return String.fromCharCode(Math.floor(Math.random() * 10 + 48));
},
function getLowerCases() {
return String.fromCharCode(Math.floor(Math.random() * 26 + 97));
},
function getUpperCases() {
return +String.fromCharCode(Math.floor(Math.random() * 26 + 65));
},
function getSpecialCharacters() {
return specialCharacters(Math.floor(Math.random() * specialCharacters.length));
}
];
// Checks to make sure user selected ok for all and uses empty minimums from above
if (numbers === true) {
minimumNumbers = functionArray[0];
minimumCount++;
}
if (lowerCases === true) {
minimumLowerCases = functionArray[1];
minimumCount++;
}
if (upperCases === true) {
minimumUpperCases = functionArray[2];
minimumCount++;
}
if (special === true) {
minimumSpecialCharacters = functionArray[3];
minimumCount++;
}
// empty string variable for the for loop below
var randomPasswordGenerated = "";
// loop getting random characters
for (let i = 0; i < (parseInt(passwordLength) - minimumCount); i++) {
var randomNumberPicked = Math.floor(Math.random() * 4);
randomPasswordGenerated += functionArray[randomNumberPicked]();
}
// to make sure characters are added to the password
randomPasswordGenerated += minimumNumbers;
randomPasswordGenerated += minimumLowerCases;
randomPasswordGenerated += minimumUpperCases;
randomPasswordGenerated += minimumSpecialCharacters;
return randomPasswordGenerated;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Password Generator</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="wrapper">
<header>
<h1>Password Generator</h1>
</header>
<div class="card">
<div class="card-header">
<h2>Generate a Password</h2>
</div>
<div class="card-body">
<textarea readonly id="password" placeholder="Your Secure Password" aria-label="Generated Password"></textarea>
</div>
<div class="card-footer">
<button id="generate" class="btn">Generate Password</button>
</div>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
Firstly, I should say you have syntax error with **// Generator functions**. I have modified your codes a little bit, compare with mine...
// Special characters for the function created
const specialCharacters = "!##$%^&*()";
const generateButton = document.getElementById('generateBtn')
generateButton.addEventListener('click', writePassword)
// Write password to the #password input
function writePassword() {
var password = generatePassword();
var passwordText = document.querySelector("#password");
passwordText.value = password;
}
// Prompts that come up after you click generate password
function generatePassword() {
var passwordLength = prompt("Please enter the number of characters you want for you new password. It must be more than 12 but less than 128.");
var numbers = confirm("Do you want numbers in your password?");
var lowerCases = confirm("Do you want lowercases in your password?");
var upperCases = confirm("Do you want uppercases in your password?");
var special = confirm("Do you want special characters in your password?");
// this is a minimum count for numbers, lowerCases, upperCases & specialCharacters
var minimumCount = 0;
// Empty minimums for numbers, lowerCases, upperCases & specialCharacters
var minimumNumbers = "";
var minimumLowerCases = "";
var minimumUpperCases = "";
var minimumSpecialCharacters = "";
// Generator functions**
var functionArray = {
getNumbers: function() {
return String.fromCharCode(Math.floor(Math.random() * 10 + 48));
},
getLowerCases: function() {
return String.fromCharCode(Math.floor(Math.random() * 26 + 97));
},
getUpperCases: function() {
return String.fromCharCode(Math.floor(Math.random() * 26 + 65));
},
getSpecialCharacters: function() {
return specialCharacters[Math.floor(Math.random() * specialCharacters.length)]
}
};
// Checks to make sure user selected ok for all and uses empty minimums from above
if (numbers === true) {
minimumNumbers = functionArray.getNumbers();
minimumCount++;
}
if (lowerCases === true) {
minimumLowerCases = functionArray.getLowerCases();
minimumCount++;
}
if (upperCases === true) {
minimumUpperCases = functionArray.getUpperCases();
minimumCount++;
}
if (special === true) {
minimumSpecialCharacters = functionArray.getSpecialCharacters();
minimumCount++;
}
// empty string variable for the for loop below
var randomPasswordGenerated = "";
// loop getting random characters
for (let i = 0; i < (parseInt(passwordLength) - minimumCount); i++) {
var randomNumberPicked = Math.floor(Math.random() * 4);
randomPasswordGenerated += randomNumberPicked;
}
// to make sure characters are added to the password
randomPasswordGenerated += minimumNumbers;
randomPasswordGenerated += minimumLowerCases;
randomPasswordGenerated += minimumUpperCases;
randomPasswordGenerated += minimumSpecialCharacters;
return randomPasswordGenerated;
}
<div class="wrapper">
<header>
<h1>Password Generator</h1>
</header>
<div class="card">
<div class="card-header">
<h2>Generate a Password</h2>
</div>
<div class="card-body">
<textarea id="password" placeholder="Your Secure Password" aria-label="Generated Password"></textarea>
</div>
<div class="card-footer">
<button id="generateBtn" class="btn">Generate Password</button>
</div>
</div>
</div>

Calling a JavaScript function in HTML?

I'm extremely new to JavaScript and HTML so go easy on me. I'm attempting to call a function from my external JavaScript file in my HTML file, but nothing I seem to do allows it to work.
JavaScript Code
var trueLength = false;
var password = "";
var things = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$%^&*()-=_+;':,./<>?";
var input = document.getElementById("len");
function generatePassword(passLength){
// Check to see if selected length is at least 8 characters long
while (trueLength = false){
if (passLength > 8){
trueLength = true;
} else {
passLength = prompt("Password Length must be at least 8 characters long! Please try again. ");
}
}
// Select random character from things and add to password until desired length is reached.
for(var x = 0; x <= passlength;){
var randomNum=Math.floor(Math.random()*things.length+1);
password = password + things.charAt(randomNum);
}
alert("Your password is: " + password);
document.write("<h1>Your Password</h1><p>" + password + "</p>");
}
<!DOCTYPE html>
<html>
<head>
<title>Password Generator</title>
</head>
<body>
<h1 align="center">Password Generator</h1>
<script type="text/javascript" src="PassGen.js"></script>
<script>
var x = prompt("Enter password length: ")
function generatePassword(x);
</script>
</body>
</html>
The goal is for the user to be prompted to input a password length, then generate a random password which will be alerted to the user and written on screen. However, only the header at the top of the screen is printed.
(I realize that I could just take the function out of the JavaScript file and run it normally, but I kinda wanna leave it like this so I know what to do in the future if I ever run into this situation again.)
Following is the code with Javascript inside <script> tag within HTML document. One thing you should be careful of while writing your javascript code in the HTML file is, to include your javascript code just before the ending tag of body </body>. so it get executed only when your html file is loaded. But if you add your javascript code in the starting ot html file, your JS code will be executed before the file is loaded.
<!DOCTYPE html>
<html>
<head>
<title>Generate Password</title>
</head>
<body>
<h1 align="center">Password Generated will be displayed here</h1>
<p id="password" align="center"></p>
<script>
var PasswordLength = false;
var password = "";
var passwordChoice = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$%^&*()-=_+;':,./<>?";
var input = prompt("Enter password length: ");
var pass = document.getElementById("password");
generatePassword(input);
function generatePassword(passLength){
while (PasswordLength == false){
if (passLength >= 8){
for(var x = 0; x < passLength;x++){
var randomNum=Math.floor(Math.random()*passwordChoice.length+1);
password = password + passwordChoice.charAt(randomNum);
}
PasswordLength = true;
}
else {
passLength = prompt("Password Length must be 8 characters long.");
}
}
pass.innerHTML = password;}
</script>
</body>
</html>
And if you want to have your Javascript code in a separate file, which can be helpful in big programs, then you need to reference that file using <script> tag and this is the way you write it down.
var PasswordLength = false;
var password = "";
var passwordChoice = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$%^&*()-=_+;':,./<>?";
var input = prompt("Enter password length: ");
var pass = document.getElementById("password");
generatePassword(input);
function generatePassword(passLength){
while (PasswordLength == false){
if (passLength >= 8){
for(var x = 0; x < passLength;x++){
var randomNum=Math.floor(Math.random()*passwordChoice.length+1);
password = password + passwordChoice.charAt(randomNum);
}
PasswordLength = true;
}
else {
passLength = prompt("Password Length must be 8 characters long.");
}
}
pass.innerHTML = password;}
<!DOCTYPE html>
<html>
<head>
<title>Generate Password</title>
<script src=""></script>
</head>
<body>
<h1 align="center">Password Generated will be displayed here</h1>
<p id="password" align="center"></p>
</body>
</html>
In your code there are the following problems :
1) Change function generatePassword(x); to generatePassword(x.length);
2) Change trueLength = false to trueLength === false
3) Change for(var x = 0; x <= passlength;){ to for(var x = 0; x < passLength; x++){
passlength => passLength , x<= to x< , insert x++
4) Change Math.floor(Math.random()*things.length+1); to Math.floor(Math.random()*(things.length)+1)
5) insert passLength = passLength.length; to else
var trueLength = false;
var password = "";
var things = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$%^&*()-=_+;':,./<>?";
var input = document.getElementById("len");
var x = prompt("Enter password length: ")
generatePassword(x.length);
function generatePassword(passLength){
// Check to see if selected length is at least 8 characters long
while (trueLength == false){
if (passLength > 8){
trueLength = true;
} else {
passLength = prompt("Password Length must be at least 8 characters long! Please try again. ");
passLength = passLength.length;
}
}
// Select random character from things and add to password until desired length is reached.
for(var x = 0; x < passLength; x++){
var randomNum=Math.floor(Math.random()*(things.length)+1);
password = password + things.charAt(randomNum);
}
alert("Your password is: " + password);
document.write("<h1>Your Password</h1><p>" + password + "</p>");
}
<h1 align="center">Password Generator</h1>
You can use this code with less complexity :
var trueLength = false, password = "" ;
var things = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$%^&*()-=_+;':,./<>?";
var x = prompt("Enter password length: ")
generatePassword(x);
var input = document.getElementById("len");
function generatePassword(passLength){
while ( passLength.length < 9 )
passLength = prompt("Password Length must be at least 8 characters long! Please try again. ");
for ( var x = 0; x < passLength.length ; x++ ) {
var randomNum = Math.floor ( Math.random() * (things.length)+1 );
password = password + things.charAt(randomNum);
}
alert("Your password is: " + password);
document.write("<h1>Your Password</h1><p>" + password + "</p>");
}
<h1 align="center">Password Generator</h1>
Few things. In order to have something show up in HTML, you will need to select an HTML element in JavaScript. Next, you used 'passlength' instead of 'passLength' in the for loop. Third, when you write function generatepassword it is invalid syntax as Lux said. Lastly, your for loop doesn't go anywhere because you don't have a third expression. Which should be changed to
for(var x = 0; x <= passLength;x++)
Edit: Another thing I forgot was trueLength = false should be changed to trueLength == false or trueLength === false.
With all that said, here's my solution:
<!DOCTYPE html>
<html>
<head>
<title>Password Generator</title>
</head>
<body>
<h1 align="center">Password Generator</h1>
<p align="center"></p>
<!--script type="text/javascript" src="PassGen.js"></script-->
<script>
var trueLength = false;
var password = "";
var things = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$%^&*()-=_+;':,./<>?";
//var input = document.getElementById("len");
var ppass = document.querySelector("p");
function generatePassword(passLength){
while (trueLength == false){
if (passLength > 8){
trueLength = true;
} else {
passLength = prompt("Password Length must be at least 8 characters long! Please try again. ");
}
}
for(var x = 0; x <= passLength;x++){
var randomNum=Math.floor(Math.random()*things.length+1);
password = password + things.charAt(randomNum);
}
//alert("Your password is: " + password);
//document.write("<h1>Your Password</h1><p>" + password + "</p>");
ppass.textContent = password;}
var x = prompt("Enter password length: ")
generatePassword(x);
</script>
</body>
</html>
What I added was a <p> tag to display the password once it's generated. I use textContent to display it once the password is done generating. And i use document.querySelector to access it.

Sign In prompt with javascript/HTML

I have this sign in prompt that allows the user to enter a valid email address and then enter a password consisting of at least one number, one special character and at least 8 or more characters. Then the user would enter the password again, and the code ensures that it matches. It also implements a strength meter to tell the user how strong the password is.
I have the meter implementing strength based on the characters entered but, I cannot figure out how to implement the length of the password. Right now if the user enters a letter, number, and special character it states that it is strong. But I need it to also have at least 8 characters as well.
This is the specific function that I believe needs adjusting;
// Function for password strength meter
function PasswordMeter(password) {
if (password.length === 0) {
document.getElementById("msg").innerHTML = "";
return;
}
var matchedCase = new Array();
matchedCase.push("[$#$!%*#?&]"); // Special Charector
matchedCase.push("[0-9]"); // Numbers
matchedCase.push("[a-z]"); // Lowercase Alphabates
var ctr = 0;
for (var i = 0; i < matchedCase.length; i++) {
if (new RegExp(matchedCase[i]).test(password)) {
ctr++;
}
}
var color = "";
var strength = "";
switch (ctr) {
case 0:
case 1:
strength = "Weak: Keep going...";
color = "red";
break;
case 2:
strength = "Medium: A little better but add more..";
color = "blue";
break;
case 3:
strength = "Strong! Now that is good!";
color = "green";
break;
}
document.getElementById("msg").innerHTML = strength;
document.getElementById("msg").style.color = color;
}
And just for better perspective this is the rest of my code... I am so close to this being perfect just need a little guidance on this one piece, so thank you in advance for any advice/help!
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<h3>Sign In</h3>
<div class="container">
<form action="/action_page.php">
<label for="userId">UserId:</label>
<input type="email" id="userId" name="email" pattern="[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,3}$" required>
<br>
<br>
<label for="psw1">Password:</label>
<input type="password" id="psw1" name="psw1" pattern="(?=.*[a-z])(?=.*[0-9])(?=.*[!##$%^&*_=+-]).{8,}" title="Must contain at least one number, one special character and at least 8 or more characters" onkeyup="PasswordMeter(this.value);"/><span id="msg"></span>
<br>
<br>
<label for="psw2">Password:</label>
<input type="password" id="psw2" name="psw2" pattern="(?=.*[a-z])(?=.*[0-9])(?=.*[!##$%^&*_=+-]).{8,}" title="Must contain at least one number, one special character and at least 8 or more characters" required>
<input type="submit" value="Submit">
</form>
</div>
<script>
//Function to check if email is valid.
function validateEmail(userId) {
var re = /\S+#\S+/;
return re.test(email);
}
userId.onchange = validateEmail;
userId.onkeyup = validateEmail;
// Function to check if both passwords is same or not.
var password = document.getElementById("psw1"), psw2 = document.getElementById("psw2");
function validatePassword(){
if(psw1.value != psw2.value) {
psw2.setCustomValidity("Passwords Don't Match");
} else {
psw2.setCustomValidity('');
}
}
psw1.onchange = validatePassword;
psw2.onkeyup = validatePassword;
// Function for password strength meter
function PasswordMeter(password) {
if (password.length === 0) {
document.getElementById("msg").innerHTML = "";
return;
}
var matchedCase = new Array();
matchedCase.push("[$#$!%*#?&]"); // Special Charector
matchedCase.push("[0-9]"); // Numbers
matchedCase.push("[a-z]"); // Lowercase Alphabates
var ctr = 0;
for (var i = 0; i < matchedCase.length; i++) {
if (new RegExp(matchedCase[i]).test(password)) {
ctr++;
}
}
var color = "";
var strength = "";
switch (ctr) {
case 0:
case 1:
strength = "Weak: Keep going...";
color = "red";
break;
case 2:
strength = "Medium: A little better but add more..";
color = "blue";
break;
case 3:
strength = "Strong! Now that is good!";
color = "green";
break;
}
document.getElementById("msg").innerHTML = strength;
document.getElementById("msg").style.color = color;
}
</script>
</body>
</html>
So your regex is already checking that the password length is at least 8 characters. The only thing you have to do is to display a message if this length is below 8 characters. I overrided the 'strength' variable with the new message, but you could also display a new one.
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<h3>Sign In</h3>
<div class="container">
<form action="/action_page.php">
<label for="userId">UserId:</label>
<input type="email" id="userId" name="email" pattern="[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,3}$" required>
<br>
<br>
<label for="psw1">Password:</label>
<input type="password" id="psw1" name="psw1" pattern="(?=.*[a-z])(?=.*[0-9])(?=.*[!##$%^&*_=+-]).{8,}" title="Must contain at least one number, one special character and at least 8 or more characters" onkeyup="PasswordMeter(this.value);"/><span id="msg"></span>
<br>
<br>
<label for="psw2">Password:</label>
<input type="password" id="psw2" name="psw2" pattern="(?=.*[a-z])(?=.*[0-9])(?=.*[!##$%^&*_=+-]).{8,}" title="Must contain at least one number, one special character and at least 8 or more characters" required>
<input type="submit" value="Submit">
</form>
</div>
<script>
//Function to check if email is valid.
function validateEmail(userId) {
var re = /\S+#\S+/;
return re.test(email);
}
userId.onchange = validateEmail;
userId.onkeyup = validateEmail;
// Function to check if both passwords is same or not.
var password = document.getElementById("psw1"), psw2 = document.getElementById("psw2");
function validatePassword(){
if(psw1.value != psw2.value) {
psw2.setCustomValidity("Passwords Don't Match");
} else {
psw2.setCustomValidity('');
}
}
psw1.onchange = validatePassword;
psw2.onkeyup = validatePassword;
// Function for password strength meter
function PasswordMeter(password) {
// here is the only part I modified
if (password.length === 0) {
document.getElementById("msg").innerHTML = "";
return;
} else if (password.length < 8) {
document.getElementById("msg").style.color = 'red';
document.getElementById("msg").innerHTML = "Your password must be at least 8 characters long";
return;
}
var matchedCase = new Array();
matchedCase.push("[$#$!%*#?&]"); // Special Charector
matchedCase.push("[0-9]"); // Numbers
matchedCase.push("[a-z]"); // Lowercase Alphabates
var ctr = 0;
for (var i = 0; i < matchedCase.length; i++) {
if (new RegExp(matchedCase[i]).test(password)) {
ctr++;
}
}
var color = "";
var strength = "";
switch (ctr) {
case 0:
case 1:
strength = "Weak: Keep going...";
color = "red";
break;
case 2:
strength = "Medium: A little better but add more..";
color = "blue";
break;
case 3:
strength = "Strong! Now that is good!";
color = "green";
break;
}
document.getElementById("msg").innerHTML = strength;
document.getElementById("msg").style.color = color;
}
</script>
</body>
</html>
I think what you want is to use different regular expressions for different strength passwords. Most regex engines have a feature called "lookarounds". They are basically assertions. I will provide you with an example using lookahead assertions.
var isEightCharactersLong = '(?=.{8,})';
var hasNumbers = '(?=.*[0-9])';
var hasLowerCase = '(?=.*[a-z])';
var hasUpperCase = '(?=.*[A-Z])';
// we're escaping the regex reserved characters using '\'
var hasSpecialCharacters = '(?=.*[!##\$%\^&])';
You can then use them to create more complex regular expressions by combining them:
// For ES6 with template strings
// 8 characters long AND has numbers AND (has lowercase OR has uppercase)
const weakPasswordRegex = new RegExp(
`^${isEightCharactersLong}${hasNumbers}(${hasLowerCase}|${hasUpperCase})$`);
// For lower ES versions
var weakPasswordRegex = new RegExp(
'^' + isEightCharactersLong + hasNumbers + '(' + hasLowerCase + '|' + hasUpperCase + ')$'
You can also extract the password strength measurement into a separate function:
function measurePasswordStrength(password) {
var weakPassword = new RegExp('<placeholder>');
var mediumPassword = new RegExp('<placeholder>');
var strongPassword = new RegExp('<placeholder>');
if (strongPassword.test(password)) return 3;
if (mediumPassword.test(password)) return 2;
if (weakPassword.test(password)) return 1;
return 0;
}
Then your PasswordMeter becomes a lot more readable and understandable:
function PasswordMeter(password) {
if (password.length === 0) {
document.getElementById("msg").innerHTML = "";
return;
}
var color = "";
var strength = "";
switch (measurePasswordStrength(password)) {
case 0:
case 1:
strength = "Weak: Keep going...";
color = "red";
break;
case 2:
strength = "Medium: A little better but add more..";
color = "blue";
break;
case 3:
strength = "Strong! Now that is good!";
color = "green";
break;
}
document.getElementById("msg").innerHTML = strength;
document.getElementById("msg").style.color = color;
}

Categories

Resources