JavaScript Login/Register Not Validating session Storage - javascript

I am trying to use data retrieved from session storage to validate a newly registered user. It just needs to be in session storage for this project. Basically, the new user registers on a Signup Page; the email and password are saved in session storage; then they should be able to log in through the regular login page as long as the tab is opened. Even though the user input is set in the session storage, I am unable to validate the user in the regular login screen afterwards. I keep receiving the error "username/password do not match". What am I missing that is causing it not to validate? Any help is much appreciated.
JavaScript
// TISSUE Login Script
//Function called when form is submitted
//Validates form and allows login
function validate() {
'use strict';
var UserName = document.getElementById('UserName').value;
var email = "adrian#tissue.com";
var email1 = "admin#tissue.com";
var Password = document.getElementById('Password').value;
var pass = "welcome1";
var pass1 = "admin123";
// stored data from the register-form
var storedName = sessionStorage.getItem('email');
var storedPw = sessionStorage.getItem('password');
// entered data from the login-form
var userName = document.getElementById('UserName');
var userPw = document.getElementById('Password');
if ((UserName == email) && (Password == pass)) {
window.location.href = "Issues.html";
return false;
} else if ((UserName == email1) && (Password == pass1)) {
window.location.href = "subscription_dashboard.html";
return false;
} else if ((userName == storedName) && (password == storedPw)) {
window.location.href = "Issues.html";
return false;
} else {
alert("username and/or password do not match");
return false;
}
}
// End of Validation
function init() {
'use strict';
if (document && document.getElementById) {
var loginform = document.getElementById('loginform');
loginform.onsubmit = validate;
}
}
window.onload = init;
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>Tissue: Titan Issue Tracking</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Issue Tracking System"/>
<meta name="author" content="Stephen Morris">
<link rel="stylesheet" type="text/css" href="tissue.css">
<script type="text/javascript" src="js/login.js"></script>
</head>
<body>
<div id="wrapper">
<h2>TISSUE: Titan Issue Tracker</h2>
<div class="topnav">
Home
SignUp
</div>
<div id="loginwrap">
<h1>Login</h1>
</div>
<div id="signupForm">
<form action="Issues.html" method="post" id="loginform" onsubmit="return validate()">
<div class="labels">
<label for="UserName">UserName:</label>
</div>
<div class="rightTab">
<input type="email" name="UserName" id="UserName" class="input-field" placeholder="E-mail Address" required>
</div>
<div class="labels">
<label for="Password">Password:</label>
</div>
<div class="rightTab">
<input type="password" name="Password" id="Password" class="input-field" placeholder="Password" required>
</div>
<div id="loginwrap">
<hr>
<input class="button" type="submit" value="Submit">
</div>
</form>
</div>
</div>
<div class="copyright">
Copyright © 2018 Titan Issue Tracker
</div>
</body>
</html>
New User JavaScript
// UserStore Module
// Store Username and Password in sessionStorage
function newUser () {
var userName = document.getElementById('email').value;
var password = document.getElementById('password').value;
sessionStorage.setItem("userName", userName);
sessionStorage.setItem("password", password);
}
New User Registration HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>Tissue: Titan Issue Tracking</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Issue Tracking System"/>
<meta name="author" content="Stephen Morris">
<link rel="stylesheet" type="text/css" href="tissue.css">
<script type="text/javascript" src="js/test.js"></script>
</head>
<body>
<div id="wrapper">
<h2>TISSUE: Titan Issue Tracker</h2>
<div class="topnav">
Home
Login
</div>
<div id="loginwrap">
<h1>Create New Account</h1>
</div>
<div id="signupForm">
<form action="Issues.html" method="post" id="loginform" onsubmit="return newUser()">
<div class="labels">
<label for="email">* E-mail:</label>
</div>
<div class="rightTab">
<input type="email" name="email" id="email" class="input-field" placeholder="Enter Your E-mail" required>
</div>
<div class="labels">
<label for="Password">* Password:</label>
</div>
<div class="rightTab">
<input type="password" name="password" id="password" class="input-field" placeholder="Create Password" required>
</div>
<div class="labels">
<label for="password">* Confirm Password:</label>
</div>
<div class="rightTab">
<input type="password" name="password" id="password1" class="input-field" placeholder="Confirm Password" required>
</div>
<div id="loginwrap">
<hr>
<input class="button" type="submit" value="Submit">
</div>
</form>
</div>
</div>
<div class="copyright">
Copyright © 2018 Titan Issue Tracker
</div>
</body>
</html>

I think the problem is you're setting storage with a name and trying to get item with another key name e.g:
sessionStorage.setItem("userName", userName);
var storedName = sessionStorage.getItem('email');
it should be instead:
sessionStorage.setItem("userName", userName);
var storedName = sessionStorage.getItem("userName");
or
sessionStorage.setItem("email", userName);
var storedName = sessionStorage.getItem("email");
Hope it helps.

Related

access table from PHP database in Javascript

I have created a login page that allows you to log in using username and password. However, it is currently so that you are always redirected to the "profile" page and there is then checked by PHP whether the login data are correct, because the data are on the DB.
Therefore I have the idea with a validate function directly on the loginpage to check if the data is correct and then I just create a session.
Does anyone have an idea how I can do this?
Here is the code:
<?php session_start();?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Login</title>
<link href="bootstrap_style.css" rel="stylesheet" id="bootstrap-css"> <!-- maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css -->
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script> <!-- //maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js or bootstrap.js-->
<script src="jquery.js"></script> <!-- //cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js -->
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="wrapper fadeInDown">
<div id="formContent">
<!-- Tabs Titles -->
<!-- Icon -->
<div class="fadeIn first">
<img src="default_logo2.png" id="icon" alt="User Icon" onclick="window.open('url', '_blank');"/>
</div>
<!-- Login Form -->
<form action="searchpage.php" method="post" onsubmit="validateForm(event);">
<input type="text" id="login" class="fadeIn second" name="username" placeholder="username">
<input type="password" id="password" class="fadeIn third" name="password" placeholder="password">
<input type="submit" class="fadeIn fourth" value="Log In">
</form>
<!-- Remind Passowrd -->
<div id="formFooter">
<a class="underlineHover" style="color:red" id="warning"></a>
</div>
</div>
</div>
</body>
</html>
<script type="text/javascript">
function validateForm(event) {
var input_username = document.getElementById("login");
var input_password = document.getElementById("password");
if (input_username.value == '' || input_username.value.charAt(0) == ' ' || input_password.value == '') {
event.preventDefault();
document.getElementById("warning").innerHTML = "Fill empty fields!";
}
else {
return true;
}
}
</script>
with this I reach the DB:
$pdo = new PDO('mysql:host=localhost;dbname=ausleihe', 'root', '');
and that is the SELECT:
$login_session = "SELECT * FROM login WHERE username = '".$hereshouldbetheusernamefromform."' AND password = '".herethepasswordfromform."'";
If you need more code or have questions, ask me!
Thx
Client-side JavaScript cannot directly access a Host-side PHP program except through AJAX calls. Only the Host-side software has access to Host-side databases.

Login system connecting with database in google spreadsheet

I'm trying to make a login system, connecting to a database in a spreadsheet.
I've tried all the ways, but in all I haven't been successful.
The system is simple, it takes the data from the form and searches the spreadsheet if the email exists, if it exists it logs in.
Can someone help me?
Follows Html code:
const GoogleSpreadsheet = require('google-spreadsheet')
{ promisify } = require('util');
const credentials = require('../credentials.json')
async function loginBase(){
const doc = new GoogleSpreadsheet('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
await promisify(doc.useServiceAccountAuth)(credentials);
const info = await promisify(doc.getInfo)();
const sheet = info.worksheets[7];
const rows = await promisify(sheet.getRows)();
var controle = false;
var email = document.getElementById("email");
for(i = 0; i < rows.length; i++){
if(rows[i].email == mail){
alert("Login realizado com sucesso");
//console.log("Usuário válidado com sucesso")
//location: "./dashboard.html"
//controle = true;
window.location.href = "http://www.devmedia.com.br";
//return true;
}
}
if(controle == false){
//alert('Usuário não encontrado');
//console.log("Usuário não encontrado");
alert("Usuário inválido");
//return false;
}
}
Follows JS code:
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/all.css">
<link rel="stylesheet" href="plugins/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="plugins/fontawesome/css/all.min.css">
<title>Holding Grupo Five</title>
</head>
<body>
<div class="login">
<div class="login-form">
<div class="login-form-wrapper">
<form id="formLogin">
<div class="mb-3">
<label for="email">Email</label>
<input type="email" class="form-control" id="email" aria-describedby="emailHelp" placeholder="Digite seu e-mail.">
</div>
<div class="mb-3">
<label for="senha" class="form-label">Senha</label>
<input type="password" class="form-control" id="senha" placeholder="Digite sua senha.">
</div>
<script src="js/login.js"></script>
<button onclick="loginBase()" type="submit" class="btn btn-primary">Login</button>
</form>
</div>
</div>
<div class="banner-login">
<img src="imagens/LogoGrupoPreto.png" alt="Grupo Five">
</div>
</div>
<script src="plugins/bootstrap/js/bootstrap.min.js"></script>
<script src="plugins/fontawesome/js/all.min.js"></script>
</body>
</html>
Could someone help me solve this problem?

Why `return()` & `onsubmit()` do not work while creating a login form to welcome page in html

While creating login form to welcome page in HTML, CSS, js the problem faced is the return statement is not working.
create code for HTML inbuilt javascript.
<!DOCTYPE html>
<html>
<head>
<title>LOGIN FORM</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="loginbox">
<img src="C:\Users\Hp\Pictures\Camera Roll\avatar2.png" class="avatar">
<h1>Login Here</h1><br>
<form action="loginbox.html" method="post" onsubmit="return validate()">
<div>
<p>user name</p>
<input type="text" name="" placeholder="Enter User name" id="user name">
</div><br>
<div>
<p>password</p>
<input type="password" name="" placeholder="Enter password" id="password">
</div><br>
<input type="submit" name="" value="login"><br>
Lost your pasword??<br>
don't have an account??
</form>
</div>
<script type="text/javascript">
var attempt = 3;
function validate()
{
var user name= document.getElementById("user name").value;
var password= document.getElementById("password").Value;
if(user name.value=="dr" && password.value=="8428")
{
return true;
}
else{
attempt --;// Decrementing by one.
alert("You have left "+attempt+" attempt;");
// Disabling fields after 3 attempts.
if( attempt == 0){
document.getElementById("username").disabled = true;
document.getElementById("password").disabled = true;
document.getElementById("submit").disabled = true;
return false;
}
}
</script>
</body>
</html>
Using return false statement it should stop entering into welcome page, but in this code it's not working, it goes to next page.
Tried that onsubmit="return false; validate();" while using this code entire block gets stop & won't enter to welcome page.
You are using spaces in your id attribute which is incorrect, the id attribute must not have anykind of spaces. Plus, you are missing id="submit" on the submit button. In your code the JS is unable to execute this line
document.getElementById("submit").disabled = true;
Because the submit button doesn't have any ID.
Below has the errors fixed. This should work
<!DOCTYPE html>
<html>
<head>
<title>LOGIN FORM</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="loginbox">
<img src="C:\Users\Hp\Pictures\Camera Roll\avatar2.png" class="avatar">
<h1>Login Here</h1><br>
<form action="loginbox.html" method="post" onsubmit="return validate()">
<div>
<p>user name</p>
<input type="text" name="" placeholder="Enter User name" id="username">
</div><br>
<div>
<p>password</p>
<input type="password" name="" placeholder="Enter password" id="password">
</div><br>
<input type="submit" name="" value="login" id="submit"><br>
Lost your pasword??<br>
don't have an account??
</form>
</div>
<script type="text/javascript">
var attempt = 3;
function validate()
{
var username= document.getElementById("username").value;
var password= document.getElementById("password").Value;
if(username == "dr" && password == "8428")
{
return true;
}
else{
attempt --;// Decrementing by one.
alert("You have left "+attempt+" attempt;");
// Disabling fields after 3 attempts.
if( attempt == 0){
document.getElementById("username").disabled = true;
document.getElementById("password").disabled = true;
document.getElementById("submit").disabled = true;
return false;
}
}
</script>
</body>
</html>
The problem was that id was missing in submit, you have to declare id in the input that has type submit. Secondly, the logic was incorrect when you validate the form, return statement was missing in the else part when the attempt was not equal to zero.
<!DOCTYPE html>
<html>
<head>
<title>LOGIN FORM</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript">
var attempt =3;
function validateForm() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if (username == "dr" && password == "8428") {
return true;
} else {
attempt--;// Decrementing by one.
alert("You have left " + attempt + " attempt!");
// Disabling fields after 3 attempts.
if (attempt == 0) {
document.getElementById("username").disabled = true;
document.getElementById("password").disabled = true;
document.getElementById("submit").disabled = true;
return false;
}
return false;
}
}
</script>
</head>
<body>
<div class="loginbox">
<h1>Login Here</h1><br>
<form action="/loginbox.html" name="myForm" onsubmit="return validateForm()">
<div>
<p>user name</p>
<input type="text" name="userName" placeholder="Enter User name" id="username">
</div><br>
<div>
<p>password</p>
<input type="password" name="password" placeholder="Enter password" id="password">
</div><br>
<input type="submit" id="submit" value="login"><br>
Lost your pasword??<br>
don't have an account??
</form>
</div>
</body>
</html>

HTML/JS Script to validate login form fails on submit

I am trying to write a html/js script to validate a simple login page and on successful login, to redirect to the homepage. What I have so far is not doing the intended when I hit the submit button. Can someone please help? It is much appreciated. My code is:
<!doctype html>
<!-- This is is the main start page saved in index.html -->
<html lang="en-US">
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<body>
<h2>Login details</h2>
<form name="login" action="return validateForm()" action="http://localhost:8080/index.html" method="post">
<fieldset>
<label for="username">Username:</label><br>
<input type="text" id="username" name="username"><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password"><br><br>
<input type="submit" value="Submit">
</fieldset>
</form>
</body>
</html>
<script>
function validateForm() {
var un = document.login.username.value;
var pw = document.login.password.value;
var username = "username"
var password = "password"
if ((un == username) && (pw == password)) {
return true;
}
else {
alert ("Login was unsuccessful, please check your username and password");
return false;
}
}
</script>
With the input from Don't Panic and Ahmed I have corrected the code:
<!doctype html>
<!-- This is is the main start page saved in index.html -->
<html lang="en-US">
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<body>
<h2>Login details</h2>
<form name="login" onsubmit="return validateFormOnSubmit()" action="http://localhost:8080/index.html" method="post">
<fieldset>
<label for="username">Username:</label><br>
<input type="text" id="username" name="username"><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password"><br><br>
<input type="submit" value="Submit">
</fieldset>
</form>
</body>
</html>
<script>
function validateFormOnSubmit() {
var un = document.login.username.value;
var pw = document.login.password.value;
var username = "username"
var password = "password"
if ((un == username) && (pw == password)) {
return true;
}
else {
alert ("Login was unsuccessful, please check your username and password");
return false;
}
}
</script>

Validation in javascript is not working as it should

I have been trying to solve the problem that I am having with this email validation in JavaScript, but all the code I have tried was having the same problem. When I used the developer tool in google chrome I didn't see any error message, so I don't understand why is this happening. I want to show the error message if an email is not valid.
What am I missing?
link full code - https://jsfiddle.net/lmanhaes/cq1g5dyt/14/
Thanks.
function checkEmail(validate) {
let re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
let email = validate.userName.value;
if (email === re)
return true;
else {
error.setAttribute("class", "error");
error.innerHTML = ("Email is not correct. Please retype.");
}
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript</title>
<link rel="stylesheet" href="css/styles.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<section>
<h1></h1>
<ul>
</ul>
<h1>Register</h1>
<p>* = Required Field</p>
<div id="formcontainer">
<form id="registerDetails" action="lmanha01_fma_t3confirm.html">
<div>
<label for="username">* Userame:</label>
<input type="text" id="userName" required>
<!--pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$"-->
<!--check that the user has in fact typed in an email address-->
<div id="error"></div>
</div>
<div>
<label for="password">* Password (must be 8 characters exactly and include one Uppercase, one
lowercase and
one number):</label>
<input type="password" id="password" pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,8}$"
required>
<input type="checkbox" id="showpasswords" onclick="Toggle()">
<!--This creates a toggle effect-->
<label id="showpasswordslabel" for="showpasswords">Show passwords</label>
</div>
<div>
<label for="retypedpassword">* Retype your password:</label>
<input type="password" id="retypedpassword">
<span id="passwordmatcherror"></span>
</div>
<div>
<button type="submit" id="registerButton">Register</button>
</div>
</form>
</div>
</section>
<!--moved to the bottom to load the page faster-->
<script src="scripts/exemple.js"></script>
</body>
</html>
You should use test() method of regex to return true or false if input value matches the email pattern.
if (re.test(email)){
//logic when it is valid
}
else{
//logic when it is invalid
}
const email = document.getElementById('email');
function validate(){
const regex=/^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
return regex.test(email.value) ?console.log("Valid"):console.log("Invalid");
}
<input type="email" id="email" />
<button onclick="validate()">
Validate
</button>

Categories

Resources