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;
}
Related
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>
<!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.
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>
I am trying to validate a password input field with minimum length of 8 characters and must contain at least 1 uppercase, 1 lowercase, 1 digit, and 1 special character.
[If the password is valid, the label becomes green. If it's not valid the label becomes red.]
I think I got the minimum length part, but I'm not sure if I'm implementing my Javacsript correctly for the other requirements.
function green() {
var pw = document.getElementById('password').value;
var pattern = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[#$!%*?&])[A-Za-z\d#$!%*?&]{8,}$";
if (pw.value == pattern) {
document.getElementById('pw').style.color = "Green";
document.getElementById('pw').innerHTML = "Password: ✔";
} else {
document.getElementById('pw').style.color = "Black";
document.getElementById('pw').innerHTML = "Password:";
}
}
<label id="pw" for="password">Password:</label>
<input id="password" name="password" minlength="8" maxlength="50" class="form-control" type="password" onkeyup="green()" value="" />
Your pattern is OK, but you need to consistently select the elements' and their properties, and call the appropriate methods on the appropriate variables:
var pw = document.getElementById('password').value;
will put the value (string) into the pw variable, so
if (pw.value == pattern) {
doesn't make sense - strings don't have a .value property.
To define a regular expression object, use / syntax, for example
var pattern = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[#$!%*?&])[A-Za-z\d#$!%*?&]{8,}$/;
not string syntax (" delimiters), else you'll just have a string.
To test if a string passes a regular expression, you can call .test on the regular expression, passing the string you want to test.
The string you assign to style.color should be lowercased, not title-cased:
function green() {
var pwText = document.getElementById('password').value;
var pwElm = document.getElementById('pw');
var pattern = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[#$!%*?&])[A-Za-z\d#$!%*?&]{8,}$/;
if (pattern.test(pwText)) {
pw.style.color = "green";
pw.innerHTML = "Password: ✔";
} else {
pw.style.color = "black";
pw.innerHTML = "Password:";
}
}
<label id="pw" for="password">Password:</label>
<input id="password" name="password" minlength="8" maxlength="50" class="form-control" type="password" onkeyup="green()" value="" />
Also, you might consider making it clear to the user that the inputted password is not sufficient, perhaps color the element red when it's not good enough:
function green() {
var pwText = document.getElementById('password').value;
var pwElm = document.getElementById('pw');
var pattern = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[#$!%*?&])[A-Za-z\d#$!%*?&]{8,}$/;
if (pattern.test(pwText)) {
pw.style.color = "green";
pw.textContent = "Password: ✔";
} else {
pw.style.color = "red";
pw.textContent = "Password: ❌";
}
}
<label id="pw" for="password">Password:</label>
<input id="password" name="password" minlength="8" maxlength="50" class="form-control" type="password" onkeyup="green()" value="" />
I've never been good at reading/writing regex. I rather go with having the different type of characters in different strings. This is alot more code than with regex, but readability should be okayish.
function green() {
var password = document.getElementById('password').value;
var lowercase = 'abcdefgh.....xyz';
var uppercase = 'ABCDEFGH.....XYZ';
var digit = '1234567890';
var special = '§!"#¤%&/()=?#£$€{[]}+.....,<>;:_';
var valid = true;
if (!containsValidCharacter(password, lowercase)) {
valid = false;
}
if (!containsValidCharacter(password, uppercase)) {
valid = false; }
if (!containsValidCharacter(password, special)) {
valid = false;
}
if (!containsValidCharacter(password, digit)) {
valid = false;
}
if (password.length < 8) {
valid = false;
}
if (valid) {
document.getElementById('pw').style.color = "Green";
document.getElementById('pw').innerHTML = "Password: ✔";
} else {
document.getElementById('pw').style.color = "Black";
document.getElementById('pw').innerHTML = "Password:";
}
}
function containsValidCharacter(stringToTest, validCharacters) {
for (var i = 0; i < stringToTest.length; i++) {
if (validCharacters.indexOf(stringToTest.charAt(i)) !== -1) {
return true;
}
}
return false;
}
I am pretty sure that there is a neat way of simplifying that function. Good luck.
I'm a new developer and I'm actually trying to do a password who check while typing if there are the good characters.
For this, I did RegExp, for uppercase, numbers, and special characters.
Uppercase and numbers working well but I don't know why special characters won't work.
HTML
<input type="text" class="input">
<p class="maj">uppercase</p>
<p class="number">number</p>
<p class="carspe">special chracters</p>
<p class="carac">min 8 characters</p>
CSS
.maj{
color:red;
}
.number{
color:red;
}
.carac{
color:red;
}
.carspe {
color:red;
}
JS
var input = document.querySelector('.input');
var maj = document.querySelector('.maj');
var number = document.querySelector('.number');
var carspe = document.querySelector('.carspe');
var carac = document.querySelector('.carac');
var uppercase = /[A-Z]/g;
var numbers = /[0-9]/g;
var carspe = /[!##$%^&*(),.?":{}|<>]/g;
input.addEventListener('input', function() {
if (input.value.match(uppercase)) {
maj.style.color = 'green';
} else {
maj.style.color = 'red';
}
if (input.value.match(numbers)) {
number.style.color = 'green';
} else {
number.style.color = 'red';
}
if (input.value.length >= 8) {
carac.style.color = 'green';
} else {
carac.style.color = 'red';
}
if (input.value.match(carspe)) {
carspe.style.color = 'green';
} else {
carspe.style.color = 'red';
}
})
Thanks for take time to learn my problem and for the future help <3