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)
}
}
Related
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");
}
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 trying to write a function that gives a user 4 choices, does what they choose and then asks them the first 4 choices again and again until they exit.
I have tried using an if/else loop inside a while loop, but that just takes the first user input and loops at that point. It also concatenates the balance when I try to add the two numbers. I assume that due to the fact that the prompt is a string and assigns a string to the variable. I am using console.log() to try and see what is happening while everything is running, but to no avail.
Sorry if this is a lengthy post and redundant.
let balance = 0;
let deposit = 0;
let withdraw = 0;
function bankFunction (banked) {
alert('Hello, how can I help you today?');
let input = prompt('Q to quit the application \nW to withdraw \nD to deposit \nB to view balance');
while (input != 'Q') {
if (input === 'W') {
withdraw = prompt("Withdraw how much?");
console.log(withdraw);
balance = balance - withdraw;
console.log(balance);
} else if (input === 'D') {
deposit = prompt("Deposit how much?");
console.log(deposit);
balance = balance + withdraw;
console.log(balance);
} else {
alert("done");
break;
}
}
}
If you want to continuously prompt the user for inputs, then the prompt function should be inside your loop too. The essential pseudo code is: "While the input is not "Q", continue to prompt for a user choice".
Implementation:
let input = "A" // Initial input to get the loop working
while (input !== "Q") {
// Get actual user input
input = prompt("Choose Q or W or D or B");
if (input === "W") {
// Withdraw logic
}
else if (input === "D") {
// Deposit logic
} else if (input === "B") {
// ...
}
}
Note that there is a bit of a little gimmick here: I needed to have an initial input ("A") to get the first round of the loop working - since in the first round of the loop, user input has not been received yet. Once it get past that initial first round, the input variable is being continuously re-assigned through the user prompt, and the loop will exactly how the pseudo-code described it.
If you don't like that gimmick, there is another way, called the While-True-Break loop. The essential idea is that: The loop will automatically run forever, until you explicitly stop it (via break statement)
let input;
while (true) {
input = prompt("Choose Q or W or B or D");
if (input === "Q") {
// Stop the program loop
break;
} else if (input === "W") {
// ...
} else if ...
}
I have a strange issue where I have two event handlers for two separate buttons on two webpages. I wouldn't think that the first one would affect the second one, but when the first one is present, the second one does not fire when the connected button is pressed. When I switch the order, the first one will always fire but the second will not. If I delete the first one, the second one fires. Here is my code:
function calculateBMI() {
var weight = parseInt(document.getElementById("Weight").value);
var height = parseInt(document.getElementById("Height").value);
//Invalid input check
if (weight < 0 || weight > 750) {
alert("Weight must be greater than 0 and less than or equal to 750");
return;
}
if (height < 0 || height > 100) {
alert("Height must be greater than 0 and less than or equal to 100");
return;
}
var resultArea = document.getElementById("Result");
resultArea.value = (weight * 703) / (height * 2);
}
document.getElementById("submit").addEventListener("click", calculateBMI);
function validateInput() {
var number1 = document.getElementById("Start").value;
var number2 = document.getElementById("End").value;
if (!isNaN(number1) || !isNaN(number2)) {
alert("Sorry, you must enter a valid number");
return false
}
else if (number1 < 0 || number2 < 0) {
alert("Sorry, you must enter a positive number");
return false;
}
else if (number2 < number1) {
alert("Sorry, the second number must be greater than the first number");
return false;
}
else {
return true;
}
}
function displayPrimeNumbers() {
if (validateInput()) {
alert("Test");
}
}
document.getElementById("getPrimed").addEventListener("click", displayPrimeNumbers);
<input id="submit" type="submit" name="submit">
<input id="getPrimed" type="button" value="Get Primes" name="getPrimed">
When I press the getPrimed button, 'Test' is not outputted in the window by alert even though the validateInput function returns true. I also get this error in the firefox console from line 25 of my code (The first addEventListener):
Uncaught TypeError: document.getElementById(...) is null
I hope this is enough information to help solve my problem!
Check for the existence of the various button elements before trying to use .addEventListener()
What is happening is if the first one in your file doesn't exist, the error prevents the rest of the code executing in order to get to the next one
Simple example
var sub = document.getElementById("submit");
// null if doesn't exist, truthy element if it does
if (sub) {
sub.addEventListener("click", calculateBMI);
}
The objective here is for the user to enter a number to determine whether it is even or to enter 'q' to quit the program.
var readlineSync = require('readline-sync');
var i = 0;
while (i <= 3) {
var num = readlineSync.question("Enter q to quit, or enter an integer to continue?");
if (num === 'q') {
console.log("You have quit the application. Thanks for using.");
break;
}
else if (num % 2) {
console.log("You have entered an odd number");
}
else if (num !== 'q') {
console.log("You have not entered a valid character. Please try again.");
break;
}
else {
console.log("You have entered an even number.");
break;
}
}
Pressing q initiates the appropriate response and exits the program. Entering an odd number also generates the appropriate response. However if an even number is entered, the program does not generate the appropriate response and instead reads You have not entered a valid character. Please try again. What am I overlooking? Any advice is appreciated.
It's because of your third condition (num !== 'q'). It evaluates as true when you enter an even number.