The expected number of <li> tags (error messages) should be six, but I am only getting three. Does anyone have a clue about how I can fix my code? Here is what I am basically trying to do:
Perform the following form validations in the order provided and display all error messages that apply:
Ensure a full name with a length greater than or equal to 1 was provided
Otherwise, display "Missing full name."
Ensure that an email address was provided and that the email address matches the regular expression:
/^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,5}$/
Otherwise, display "Invalid or missing email address."
Ensure the password has 10 to 20 characters
Otherwise, display "Password must be between 10 and 20 characters."
Ensure the password contains at least one lowercase character (use a regular expression)
Otherwise, display "Password must contain at least one lowercase character."
Ensure the password contains at least one uppercase character (use a regular expression)
Otherwise, display "Password must contain at least one uppercase character."
Ensure the password contains at least one digit (use a regular expression)
Otherwise, display "Password must contain at least one digit."
Ensure the password and confirmation password match
Otherwise, display "Password and confirmation password don't match."
"use strict";
function checkForm() {
const fullNameInput = document.getElementById("fullName");
const emailInput = document.getElementById("email");
const passwordInput = document.getElementById("password");
const passwordConfirmInput = document.getElementById("passwordConfirm");
const formErrorsDiv = document.getElementById("formErrors");
// Reset errors and remove classes
formErrorsDiv.innerHTML = "";
fullNameInput.classList.remove("error");
emailInput.classList.remove("error");
passwordInput.classList.remove("error");
passwordConfirmInput.classList.remove("error");
// Error messages in <li> tags
const errorMessages = {
fullName: "Missing full name.",
email: "Invalid or missing email address.",
passwordLength: "Password must be between 10 and 20 characters.",
passwordLowercase: "Password must contain at least one lowercase character.",
passwordUppercase: "Password must contain at least one uppercase character.",
passwordDigit: "Password must contain at least one digit.",
passwordConfirm: "Password and confirmation password don't match."
};
const errors = [];
// Check full name
if (fullNameInput.value.trim().length === 0) {
errors.push("fullName");
fullNameInput.classList.add("error");
}
// Check email
const emailRegex = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,5}$/;
if (!emailRegex.test(emailInput.value.trim())) {
errors.push("email");
emailInput.classList.add("error");
}
// Check password
const password = passwordInput.value;
const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{10,20}$/;
if (password.length < 10 || password.length > 20) {
errors.push("passwordLength");
passwordInput.classList.add("error");
} else if (!password.match(/[a-z]/)) {
errors.push("passwordLowercase");
passwordInput.classList.add("error");
} else if (!password.match(/[A-Z]/)) {
errors.push("passwordUppercase");
passwordInput.classList.add("error");
} else if (!password.match(/\d/)) {
errors.push("passwordDigit");
passwordInput.classList.add("error");
}
// Check password confirmation
if (passwordConfirmInput.value !== password) {
errors.push("passwordConfirm");
passwordConfirmInput.classList.add("error");
}
if (errors.length > 0) {
// Display error messages
const errorList = document.createElement("ul");
errors.forEach(error => {
const errorMessage = document.createElement("li");
errorMessage.innerText = errorMessages[error];
errorList.appendChild(errorMessage);
});
formErrorsDiv.appendChild(errorList);
formErrorsDiv.classList.remove("hide");
} else {
formErrorsDiv.classList.add("hide");
}
}
document.getElementById("submit").addEventListener("click", function(event) {
checkForm();
// Prevent default form action. DO NOT REMOVE THIS LINE
event.preventDefault();
});
The problem appears here:
if (password.length < 10 || password.length > 20) {
errors.push("passwordLength");
passwordInput.classList.add("error");
} else if (!password.match(/[a-z]/)) {
errors.push("passwordLowercase");
passwordInput.classList.add("error");
} else if (!password.match(/[A-Z]/)) {
errors.push("passwordUppercase");
passwordInput.classList.add("error");
} else if (!password.match(/\d/)) {
errors.push("passwordDigit");
passwordInput.classList.add("error");
}
Change it to:
if (password.length < 10 || password.length > 20) {
errors.push("passwordLength");
passwordInput.classList.add("error");
}
if (!password.match(/[a-z]/)) {
errors.push("passwordLowercase");
passwordInput.classList.add("error");
}
if (!password.match(/[A-Z]/)) {
errors.push("passwordUppercase");
passwordInput.classList.add("error");
}
if (!password.match(/\d/)) {
errors.push("passwordDigit");
passwordInput.classList.add("error");
}
Related
I am new to JavaScript and I'm currently creating a password generator for a project. I am running into a problem where when the user is prompted with confirm messages to select their ideal password criteria. I want to return an alert message to the window with a loop function if they don't choose at least one option. Here is what I have so far.
// function: when you click on generate button it prompts messages to select password criteria.
var generateBtnPrompt = function () {
var confirmNumber = confirm("Click 'OK' to generate numbers in your password");
var confirmLowerCase = confirm("Click 'OK' to generate lowerCase characters in your password");
var confirmUpperCase = confirm("Click 'OK' to generate upperCase characters in your password");
var confirmSymbols = confirm("Click 'OK' to generate symbols characters in your password");
//parseInt convert a string into an integer
var charLength = parseInt(prompt("How many characters would you like your password to be? Please choose a number from (8-128)"));
};
You can use the Logical OR operator (||) to check that at least one of the variables are true.
MDN Web Docs:
The logical OR (||) operator (logical disjunction) for a set of
operands is true if and only if one or more of its operands is true.
And recursion to re-run the function if none of the variables are true.
Like this:
if (!(confirmNumber || confirmLowerCase || confirmUpperCase)) {
alert("You need to pick at least one!");
return generateBtnPrompt()
}
Full code:
var generateBtnPrompt = function () {
var confirmNumber = confirm("Click 'OK' to generate numbers in your password");
var confirmLowerCase = confirm("Click 'OK' to generate lowerCase characters in your password");
var confirmUpperCase = confirm("Click 'OK' to generate upperCase characters in your password");
var confirmSymbols = confirm("Click 'OK' to generate symbols characters in your password");
if (!(confirmNumber || confirmLowerCase || confirmUpperCase)) {
alert("You need to pick at least one!");
return generateBtnPrompt()
}
var charLength = parseInt(prompt("How many characters would you like your password to be? Please choose a number from (8-128)"));
};
generateBtnPrompt()
i want to validate a password field with the following conditions:
One uppercase character
One lowercase character
One number
One special character
Eight characters minimum
If the password input is correct i want to make the pass field green if not it should be red.
I tried with this code but doesnt work:
let password = document.querySelectorAll(".control-group")[3];
password.addEventListener("focusout", () => {
let inp = password.value;
if (
inp.match(/[a-z]/g) &&
inp.match(/[A-Z]/g) &&
inp.match(/[0-9]/g) &&
inp.match(/[^a-zA-Z\d]/g) &&
inp.length >= 8
) {
password.style.backgroundColor = "green";
} else {
password.style.backgroundColor = "red";
}
});
The code you provided is not working due to the fact that
inp.match(/[a-z]/g) && inp.match(/[^a-zA-Z\d]/g)
is just "false". You are telling there "if it contains alphabetic characters as well as it doesn't contains any", which is some sort of
let i = 0;
if (i == 1) {...}
As I said on one of the comments of your question, just search for another solution, like the one that #harsh-saini said.
Output of match() is not true or false, but the match thing like str or int or if it wrong it will show null. So in your case better use "if your case (if input.match() != null) as true". There is the example !
var input = "GoodMorning Sir"
if (input.match(/[0-9]/g) != null){
console.log("there are number here")
} else if (input.match(/[A-Z]/g) != null){
console.log("there are uppercase here")
}
//this is your if else code, try to console.log your condition
//as you can see it wont giving output true or false
console.log(input.match(/[A-Z]/g)) // ["G", "M" , "S"]
I am facing one small problem to set the message and clear the message.
I have 2 input where onclick of the button I should check the input fields satisfies the condition else don't show any message
OR
if error message was displaying after condition gets satisfied I should remove the message
but the code below doesn't satisfies if phnum is 10 digit and pincode is less than 7 digit and vise versa
if both field length doesn't satisfy on click of button i should display both the error messages
const inputValidation = () => {
if (phnum?.length < 10) {
//phnum must be 10 digit(error message)
if (picode?.length < 7) {
//zipcode must be 7 digit (error message)
} else {
//remove zipcode message
} else {
//remove phnum message
}
}
}
Move the clear errors before the ifs
Move the second if since now you only test picode if phnum is in error
const inputValidation = () => {
//remove zipcode message
//remove phnum message
if (phnum?.length < 10) {
//phnum must be 10 digit(error message)
}
if (picode?.length < 7) { // removing the else will show both
//zipcode must be 7 digit (error message)
}
}
I need to make sure it begins with a Z, has 8 minimum characters and has an *.
Consider this function:
function validatePassword()
{
var strPassword
//Request user enter their password then check its validity
strPassword = prompt("Please Enter A Valid Password","");
while ((strPassword.length <7) || (strPassword.indexOf('*') ==-1) || (strPassword.charAt(0) != 'Z')) {
{
alert("Your password is invalid, \n Please try again")
strPassword = prompt("Please Enter A Valid Password","");
}
//Outcome if password is valid
alert("Your password is valid")
//End while
}
}
You've got a double { at the last OR check. Too many parenthesis.
function validatePassword()
{
var strPassword = prompt("Please Enter A Valid Password","");
while ((strPassword.length <7) ||
(strPassword.indexOf('*') ==-1) ||
(strPassword.charAt(0) != 'Z'))
{
alert("Your password is invalid, \n Please try again");
strPassword = prompt("Please Enter A Valid Password","");
}
alert("Your password is valid");
}
You have strPassword.length < 7 which should be strPassword.length < 8 or does it fail on other requirements?
EDIT: I would separate out the tests for the valid password and print out a more meaningful message for each one. Then you should see why it fails.
This one is complete
http://jsfiddle.net/mplungjan/mvwRj/
function validatePassword() {
var strPassword;
//Request user enter their password then check its validity
strPassword = prompt("Please Enter A Valid Password - Starts with Z minimum 8 chars including an *","");
while (strPassword==null || strPassword.length <8 ||
strPassword.indexOf('*') ==-1 ||
strPassword.charAt(0) != 'Z') {
alert("Your password is invalid, \n Please try again")
strPassword = prompt("Please Enter A Valid Password","");
} //End while
//Outcome if password is valid
alert("Your password is valid")
}
validatePassword();
i have to create a regular expression for password in java script with the following criteria
1. The password should contain atleast one alphabet either upper case or lower case
2. It should contain atleast one number
3. It should contain atlease one special character(`,~,!,#,#,$,%,^,&,*,_,+,=)
var userpw = "musSTER123#";
var invalid = false;
if(!userpw.match(/\d/) || !userpw.match(/[a-zA-Z]/) || !userpw.match(/['~!##$%&*_+=]/))
invalid = true;
alert('pw is valid?' + !invalid);
Use these regexps:
[a-zA-Z] for at least one letter
[0-9] for at least one digit
['~!##$%&*_+=^] for at least one of the special characters you mentioned OR
[^a-zA-Z0-9] for at least one character that is neither a letter nor a digit
But even better would be to support single-sign-on with OpenID, SSL client certificates or a way to make the browser store a long password in its password storage without even showing it to the user (maybe some password input that's prefilled by javascript and hidden with CSS).
Don't require strong passwords. They are fool's gold. Yes, a strong password is better than a weak one, all other things being equal. But all other things are rarely equal. A strong password is more likely than a weak one to end up on a post-it note stuck to the user's monitor.
A far better defence is a good lock-out policy. A system that does nothing more than disallow passwords containing dictionary words, but locks IP addresses out for one hour after three failed login attempts will still be over 99% secure after one year of constant battering by brute force. Also, you can make it much stronger by increasing the lock-out period for continued failed attempts.
These posts were helpfull here is a bit of code some of you may want to use at some point. This forces the user to input an Uppercase, Lowercase, Special character, and minimum of 8 characters in length. It also breaks it up and lets them know what exactly it is they are doing wrong.
<script type="text/javascript" language="javascript">
function validate() {
if (document.aspnetForm.PasswordValue.value == '') {
alert('Current Password is a required field!');
document.aspnetForm.PasswordValue.focus()
return false;
}
if (document.aspnetForm.NewPasswordValue.value == '') {
alert('New Password is a required field!');
document.aspnetForm.NewPasswordValue.focus()
return false;
}
if (document.aspnetForm.NewPasswordValue.value.match(/\d/) == null) {
alert('Your new password must have a number!');
document.aspnetForm.NewPasswordValue.focus()
return false;
}
if (document.aspnetForm.NewPasswordValue.value.match(/[a-z]/) == null) {
alert('Your new password must have an Upper and lower case letter!');
document.aspnetForm.NewPasswordValue.focus()
return false;
}
if (document.aspnetForm.NewPasswordValue.value.match(/[A-Z]/) == null) {
alert('Your new password must have an Upper and lower case letter!');
document.aspnetForm.NewPasswordValue.focus()
return false;
}
if (document.aspnetForm.NewPasswordValue.value.match(/['~!##$%&*_+=]/) == null) {
alert('Your new password must have a special character i.e.(!##$%&*)');
document.aspnetForm.NewPasswordValue.focus()
return false;
}
if (document.aspnetForm.NewPasswordValue.value.length < 8) {
alert('Your new password must have a minimum of 8 characters!');
document.aspnetForm.NewPasswordValue.focus()
return false;
}
if (document.aspnetForm.NewConfirmPassword.value == '') {
alert('Confirm New Password is a required field!');
document.aspnetForm.NewConfirmPassword.focus()
return false;
}
if (document.aspnetForm.NewPasswordValue.value != document.aspnetForm.NewConfirmPassword.value)
{
alert('New password and Confirm New Password do not match!');
document.aspnetForm.NewConfirmPassword.focus()
return false;
}
if (document.aspnetForm.PasswordValue.value == document.aspnetForm.NewPasswordValue.value) {
alert('Your current password and new password are the same!');
document.aspnetForm.NewPasswordValue.focus()
return false;
}
}
</script>