Javascript password validation with regular expression - javascript

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>

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>

Need help clearing text area after JavaScript function is ran again

<!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.

How to validate password and confirm requirements (1 upper, 1 lower, 1 special character, 1 digit) are met?

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: &#10004";
} 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: &#10004";
} 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: &#10004";
} 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.

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;
}

Password validation while typing didn't work with special characters in Vanilla JavaScript

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

Categories

Resources