if statement passed but else statement is also executed - JavaScript - javascript

I have a login system that loops through an array of objects to fetch and compare username and password entered by the user in the login page. I have issued an if statement to check if user credentials are correct. The problem am having is that the system shows the else statement even when the if statement has passed or the user credentials are correct.
Please see the full demo in the link below;
https://jsfiddle.net/dej5sr9z/
Here is my HTML code
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE" />
<meta name="generator" content="Ayub Technologies">
<meta name="author" content="Verai Bosobori" />
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
<meta name="description" content="">
<title>Lycan CREATIONS | Home</title>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<section>
<div class="form_div">
<h2>Login</h2>
<div style="text-align:left; color:red; font-weight:bold;" id="error"></div>
<div style="text-align:left; color:green; font-weight:bold;" id="success"></div>
<br>
<form action="#">
<div class="form_input">
<label for="">Username</label>
<input type="text" id="username" placeholder="">
</div> <br>
<div class="form_input">
<label for="">Password</label>
<input type="password" id="passwd" placeholder="">
</div>
<div class="form_input">
<p style="text-align:left; color:blue;">Forgot Password?</p>
</div>
<div class="form_submit">
<button type="submit" onclick="getInfo()">Submit</button>
</div>
</form>
</div>
</section>
</body>
</html>
Beolow is the JavaCript Code
var objPeople =[
{
username: "verai",
passwd: "lycan"
},
{
username: "ayub",
passwd: "metah"
},
{
username: "chris",
passwd: "forever"
}
]
function getInfo(){
var username = document.getElementById("username").value;
var passwd = document.getElementById("passwd").value;
var error = document.getElementById("error").innerHTML;
if (username != '' || passwd != ''){
for(i = 0; i < objPeople.length; i++){
if(username == objPeople[i].username && passwd == objPeople[i].passwd){
document.getElementById("success").innerHTML = "Hello " + username + "!! You are successfully logged in!!!";
console.log(username + " is logged in!!!");
setTimeout(function(){
document.getElementById("success").innerHTML = "";
document.getElementById("username").value = "";
document.getElementById("passwd").value = "";
},5000);
}else{
document.getElementById("error").innerHTML = " Incorrect Username or Password. Please try again!";
setTimeout(function(){
document.getElementById("error").innerHTML = "";
document.getElementById("username").value = "";
document.getElementById("passwd").value = "";
},2000);
}
}
}else{
// console.log("Your username is " + username + " and your password is " + passwd );
document.getElementById("error").innerHTML = "All fields required, please try again!";
setTimeout(function(){
document.getElementById("error").innerHTML = "";
document.getElementById("username").value = "";
document.getElementById("passwd").value = "";
},2000);
}
}
I will appreciate if someone points out what am not doing right, thanks.

Assuming a correct combination has been entered, the for-loop goes into the if-part once for the matching user, but also it goes into the else-part for all other non-matching users. There is nothing in place to prevent that from happening.
You need to determine who is the one matching person if any, and then proceed with that result (which is either a user object, or undefined).
You can do so with find, using code like this:
var matchingUser = objPeople.find(p => username === p.username && passwd === p.passwd);
if (matchingUser) {
// ...
} else {
// ...
}
Side note - I used the "triple equal sign", which does an exact comparison between objects without any type conversions that could get in the way.

Related

How do we apply Bootstrap classes to JavaScript Error messages and make them stay on the screen when a form submit button is clicked?

I am trying to figure out how to make Javascript error messages be displayed in the DOM and stay there until valid information is added into the form inputs. Right now they appear for a brief moment and then disappear. On top of that, I have to use Bootstrap 5 to stylize the JavaScript Error messages. I've been trying to figure this out all day and I haven't had any luck.
I have my HTML and Javascript down below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Login Form</title>
<link rel="stylesheet" href="login/login.css">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
</head>
<body>
<main>
<h1 class="text-primary">Login</h1>
<form id="login_form" name="login_form" method="get">
<div>
<label for="email1">Email:</label>
<input name="email" type="email" autocomplete="email" id="email" class="form-control">
<span class="text-danger">*</span>
<span id="errorName"></span>
</div>
<div>
<label for="password">Password:</label>
<input name="password" type="password" autocomplete="password" id="password" class="form-control">
<span class="text-danger">*</span>
<span id="errorName"></span>
</div>
<div>
<label> </label>
<button type="submit" class="btn btn-primary" id="login">Login
</div>
</form>
</main>
</main>
<script defer src="login/login.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
</body>
</html>
const $ = selector => document.querySelector(selector);
document.addEventListener("DOMContentLoaded", () => {
$("#login").addEventListener("click", () => {
// get values user entered in textboxes
const email = $("#email");
const password = $("#password");
// create a Boolean variable to keep track of invalid entries
let isValid = true;
// check user entries - add text to error message if invalid
if (email.value == "" || password.value == "") {
email.nextElementSibling.textContent = "You seem to have forgotten your username and password.";
password.nextElementSibling.textContent = "You seem to have forgotten your username and password.";
return false;
} else {
email.nextElementSibling.textContent = "";
password.nextElementSibling.textContent = "";
}
if (email.value == "admin#example.com" && password.value == "password") {
document.writeln("Welcome back Admin!")
} else {
document.writeln("That email and password doesn't seem to be right. Try again.")
}
// submit the form if all entries are valid
if (isValid) {
$("#login_form").submit();
}
});
});

Need the output of the inputs to be pushed into the <div>

I'm trying to get the user inputs to be pushed out as a message into a <div> via the button press after confirming that all the inputs are filled and the correct password has been entered. That part works fine but my forEach is not working:
If the user has input a number value lower than 18, I want an if that types out via push "Your name is UName and you are Age years old, you are not of legal age", or else the same result as above but ending with "...you are of legal age".
Any idea how I should go forth?
let nameElement = document.getElementById("UNameInput");
let faultElement = document.getElementById("errorOutput");
let ageElement = document.getElementById("AgeInput");
let clickElement = document.getElementById("button");
let passwordElement = document.getElementById("PasswordInput");
clickElement.addEventListener("click", function(e) {
let feedback = [];
if (UNameInput.value === '' || UNameInput.value === null) {
feedback.push('Name input missing')
}
if (AgeInput.value === '' || AgeInput.value === null) {
feedback.push('Age input missing')
} else if (PasswordInput.value !== 'IHM') {
feedback.push('Password is not valid')
} else {
feedback.forEach((item, i) => {
if (item.AgeInput < 18) {
feedback.push("You are not of not legal age")
} else {
feedback.push(" You are of legal age ")
}
});
}
if (feedback.length > 0) {
e.preventDefault()
faultElement.innerText = feedback.join(", ")
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="JSny.js" defer></script>
</head>
<body>
<div id="errorOutput"></div>
<p id="output"></p>
<div>
<label for="UNameInput">Name Input</label>
<input id="UNameInput" name="name" type="text">
</div>
<div>
<label for="AgeInput">Age Input</label>
<input id="AgeInput" name="age" type="number">
</div>
<div>
<label for="PasswordInput">Password Input</label>
<input id="PasswordInput" name="password" type="password">
</div>
<button id="button">Submit</button>
</body>
</html>
You are using AgeInput instead of ageElement in the if statement.

After completing Validation on input function won't link to the next .html

I created a part of the simple website with a register page I created a validation (.js) for both and wanted to validate the input on the form so after i completed the validation criteria and fill all the input it supposed to link or open the next page (it's login page if you are in the register.html). The problem is if i don't include href to link it, it won't open the next page but the validation was successful but if i include href the validation was skipped and it instantly opens the next page which is login.html after i click on the Register button. How to put validation on the Register button so it validates the input and open the next page at the same time? (A message for a successful registration after that is also better). Here is the code for register and the register validation.
This is called registersraboet.html for the Register page.
<!DOCTYPE html>
<html>
<head>
<title>Register Sraboet</title>
<link rel="stylesheet" type="text/css"
href="css/register.css">
<script type="text/javascript" src="js/jquery-
latest.min.js"></script>
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
</head>
<body>
<div class="headerregister">
<img src="assets/logo.png">
</div>
<div class="containerregister">
<form action="" id="rgs_form">
<div id="err_msg"></div>
<label><b>Email</b></label><br>
<input type="email" placeholder="masukkan email
anda" id="emailrgs"><br>
<label><b>Username</b></label><br>
<input type="text" placeholder="masukkan nama
anda" id="usernamergs"><br>
<label><b>Password</b></label><br>
<input type="password" placeholder="masukkan
password anda" id="passwordrgs"><br>
<label><b>ID Number</b></label><br>
<input type="text" placeholder="masukkan nomor
KTP anda" id="KTPrgs"><br>
<label><b>Phone Number</b></label><br>
<input type="text" placeholder="masukkan nomor
telepon anda" id="phonergs"><br>
<div class="termsnprivacy">
<p>By creating an account you agree to
our Terms & Privacy</p>
</div>
<div class="registerbtn">
<button type="button"
onclick="validatergs()">Register</button><br>
</div>
<div class="alreadyakun">
<br><p>Sudah Punya Akun? Silahkan Login</p>
</div>
</form>
</div>
<div class="footerregister">
<div class="copyrightfooter">
<label for="Copyright">Copyright ©
Sraboet 2020</label>
</div>
</div>
<script type="text/javascript"
src="js/validationregister.js"></script>
</body>
</html>
This is called validationregister.js for the validation in register.
var err = document.getElementById('err_msg');
function validatergs(){
var email = document.getElementById('emailrgs').value;
var username =
document.getElementById('usernamergs').value;
var password =
document.getElementById('passwordrgs').value;
var ktp = document.getElementById('KTPrgs').value;
var phones = document.getElementById('phonergs').value;
if(email == ""){
err.innerHTML = "Email harus diisi!"
}
else if(username == ""){
err.innerHTML = "Nama harus diisi!"
}
else if(password == ""){
err.innerHTML = "Password harus diisi!"
}
else if(ktp == ""){
err.innerHTML = "Nomor ktp harus diisi!"
}
else if(!+(ktp)){
err.innerHTML = "nomor ktp harus angka!";
}
else if(phones == ""){
err.innerHTML = "Nomor telepon harus diisi!"
}
else if(!+(phones)){
err.innerHTML = "Nomor telepon harus angka!";
}
else {
a.href = "loginsraboet.html";
}
}
This is not the right way to write it. First you get the a node, use getelementByclass or some other method to trigger the node click() method such as let a= document.getelementbyid (#a);next a.click ()

Check if user input has certain characters

Hi I'm making a "secure password" project for school and I need help to check if a user input has "!#$%&#" and if they have it tell them their password is secure.
This is a project for school Im stuck doing this :(
var password = document.getElementById('password');
var eMsg = document.getElementById('feedback');
var minLength = 6;
function checkPass() {
if (password.value.length < minLength) {
eMsg.innerHTML = 'Password must have' + minLength + 'characters or more';
} else {
eMsg.innerHTML = '';
}
}
<html>
<head>
<title> Password Secured </title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1 class="logo"> logo</h1>
<br/>
<br/>
<p class="input">Please type your password: <br/> <input type="text" id="password" />
<div id="feedback"></div>
</p>
<br/>
<p class="answer"></p>
<br/>
<br/>
<p class="tips"> <br/>Tips tips tips </p>
</body>
</html>
You can test a string using this regular expression:
function isValid(str){
return !/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/g.test(str);
}
Possible duplicate of
javascript code to check special characters
Use a regular expression.
// Returns TRUE if the string contains one of these characters.
// Returns FALSE otherwise
/[!#$%&#]/.test(password)
Use the regular Expression
var password = document.getElementById('password');
password.addEventListener('blur',checkPass);
var eMsg = document.getElementById('feedback');
var minLength = 6;
function checkPass () {
if (password.value.length < minLength ) {
eMsg.innerHTML = 'Password must have' + minLength + 'characters or more';
} else if(/[!#$%&#]/.test(password.value)){
eMsg.innerHTML = 'Your password is secure';
}
}
<html>
<head>
<title> Password Secured </title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1 class="logo"> logo</h1>
<br></br>
<br></br>
<p class="input">Please type your password: <br></br> <input type="text" id="password"/> <div id="feedback"></div> </p>
<br></br>
<p class="answer"></p>
<br></br>
<br></br>
<p class="tips"> <br></br>Tips tips tips </p>
</body>
You are looking for a code using a regular expression.
What you should do is the following:
document.getElementById("myInput").value.match(/[\!\\#\$\%\&\#]+/g)
and check if this matched anything, if it does, then you properly matched any of those characters.

POST request to MySQL

I have this next code
<!doctype html>
<html class="">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Nieuwe gebruiker | Sociale buurt</title>
<link href="boilerplate.css" rel="stylesheet" type="text/css">
<link href="onzebuurt.css" rel="stylesheet" type="text/css">
<script type="text/javascript" language="javascript">
function formulierValideren() {
if (document.getElementById('Username').value == '' || document.getElementById('Username').value == null)
{
alert ('Gebruikersnaam is verplicht.');
document.getElementById('Username').style.borderColor = "red";
return false;
}
else if (document.getElementById('Wachtwoord').value == '' || document.getElementById('Wachtwoord').value == null)
{
alert ('Wachtwoord is verplicht.');
document.getElementById('Wachtwoord').style.borderColor = "red";
return false;
}
else if (document.getElementById('Wachtwoord2').value == '' || document.getElementById('Wachtwoord2').value == null)
{
alert ('Bevestig wachtwoord.');
document.getElementById('Wachtwoord2').style.borderColor = "red";
return false;
}
else if (document.getElementById('Wachtwoord2').value != document.getElementById('Wachtwoord').value)
{
alert ('Wachtwoorden komen niet overeen.');
document.getElementById('Wachtwoord2').style.borderColor = "red";
return false;
}
else
{
$("#bevestig").click(function() {
gebruikerToevoegen();
});
var msg = "Registratie succesvol. Klik op OK om u aan te melden op de site.";
if(confirm(msg)){
setTimeout(function() {window.location.href = "http://webs.hogent.be/kevinbaeyens/"})
}
}
//end if
}//end function
function gebruikerToevoegen() {
var request = new XMLHttpRequest();
request.open("POST", url);
request.onload = function() {
if (request.status == 201){
alert("everything OK!");
} else {
alert("you're wrong");
}
};
}
</script>
</head>
<body class="body2">
<div class="gridContainer clearfix">
<div class="header1">
<center>
Nieuwe gebruiker
</center>
</div>
<div id="formulier2">
<form method="post" name="form" action="">
<p class="labels"><center>Gebruikersnaam *</center></p><input id="Username" type="text" name="Username" placeholder="Gebruikersnaam" size="50">
<p class="labels"><center>Wachtwoord *</center></p><input id="Wachtwoord" type="password" name="Wachtwoord" placeholder="Wachtwoord" size="50">
<p class="labels"><center>Bevestig wachtwoord *</center></p><input id="Wachtwoord2" type="password" name="Bevestig wachtwoord" placeholder="Bevestig wachtwoord" size="50">
<br />
<center><img id="return" name="jsbutton" src="return.png" alt="Terug" /></center>
<br />
<center><input id="bevestig" type="image" src="Bevestig.png" width="200" height="50" border="0" alt="SUBMIT!" onclick="formulierValideren()"></center>
<br />
</form>
</div>
</div>
</body>
</html>
I want to send the data from #Username and #Wachtwoord to my MySQL database.
Please help me please, i'm stuck on this for almost a week now. i'll be so happy if anyone could help me! if i need to give more information, please ask me
first I thought you were looking for a client side solution (which woul be a very bad idea anyway). Jason is right. But if you want something kind of automatic, have a look to smarty php. Though, first you have to learn some basic stuff and a watch very clear example you could find in this video tuto: http://www.youtube.com/watch?v=gvGb5Z0yMFY
1) Why are you using a framework (seems jQuery) and dooing something like this
var request = new XMLHttpRequest();
You may have a look at: http://api.jquery.com/jQuery.ajax/
2) It would recommend, to use e.preventDefault instead of returning false on validation.
https://developer.mozilla.org/en-US/docs/DOM/event.preventDefault
3) What are you doing in your "action"? Or: where is your url pointing to?
as mentioned before: you need some kind of "endpoint" on the serverside:
http://www.springsource.org/
http://www.asp.net/
http://rubyonrails.org/
https://www.djangoproject.com/
http://framework.zend.com/
http://www.catalystframework.org/
http://www.seaside.st/
or whatever

Categories