I have a problem and it's hard, too hard for me as a beginner. Can you please help me. I know this is kinda strange creating this with javascript but it's just my own project, nothing i will put on web. But i need this problem solved by using pure Vanilla Javascript, i have
users as shown below on .js and i have a page where i need to create i new user that can be logged in as same as other two(admin and guest), i need another guest user and created based on input values...Thanks in advance, i am still learning and comments would be appreciated as well..
var el = document.getElementById("login");
if (el) {
el.addEventListener('click', state);
}
function state() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if (username == "admin" && password == "admin") {
sessionStorage.setItem("isAdmin", "yes");
alert("You are logged in as ADMIN !");
window.location.href = "../index.html";
} else if (username == "guest" && password == "guest") {
sessionStorage.setItem("isAdmin", "no");
alert("You are logged in as GUEST !");
window.location.href = "../index.html";
} else {
alert("Incorrect username or password, try again !")
}
}
<header>
<div class="container">
<div id="branding">
<h1><span id="logo">mov</span>BLANK</h1>
</div>
<nav>
<ul>
<li>Home</li>
<li><a id="newprojection" href="newprojection.html">New projection</a></li>
<li><a id="buyticket" href="buyticket.html">Buy a ticket</a></li>
<li class="current"><a id="newuser" href="newuser.html">New user</a></li>
<li><a id="loginbtn" href="login.html">Log in</a></li>
<li>
<a id="nameofuser" href="#"></a>
</li>
</ul>
</nav>
</div>
</header>
<div class="container">
<form>
<p>Username</p>
<input type="text" name="username" required>
<p>Password</p>
<input type="password" name="password" required>
<p>Repeat Password</p>
<input type="password" name="password" required>
<p>Function(admin/guest)</p>
<input type="text" name="function" required>
<a id="adduser" href="#">Add User</a>
</form>
</div>
you can save two data: value and key so add this function in your code.
function saveData() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if(!sessionStorage.getItem(username) == username) {
sessionStorage.setItem(username, password);
}else {
alert(username + "already registered");
}
}
update this
<input type="text" name="username" required id="username">
<p>Password</p>
<input type="password" name="password" required id="password">
<p>Repeat Password</p>
<input type="password" name="password" required>
<p>Function(admin/guest)</p>
<input type="text" name="function" required>
<a id="adduser" href="#" onclick="saveData();">Add User</a>
This is the logic, I hope I have helped
Try creating an array of valid users, rather than using if-else statements to check against each individual user (which can't be adapted to additional users).
const users = [
{ username: 'admin', password: 'admin' },
{ username: 'guest', password: 'guest' },
];
Then when you want to create a new user, push to that array. Verify logins with with:
function state() {
const username = document.getElementById("username").value;
const password = document.getElementById("password").value;
const foundUser = users.find(user => user.username === username && user.password === password);
if (!foundUser) {
console.log('Invalid user!');
} else {
// Log the user in
}
}
Problem is, your current code validates a user login attempt (for which there isn't a button for), which can't (or shouldn't) be the same form as the form used to register, at least not without changing things around significantly.
I made a working example, see below. The example is just for testing/learning purposes. I would recommend you to validate user and password using http requests and preventing sql injections.
PS: here is jsfiddle: https://jsfiddle.net/xdLey6cp/24/
PS2: you can use sweet alert instead of alert: https://sweetalert.js.org/guides/
<input type="text" id="txt_user" placeholder="user">
<!--you should use type=password here, but set as text for test purposes-->
<input type="text" id="txt_password" placeholder="password">
<input type="submit" id="createuser" value="create user">
<input type="submit" id="validateuser" value="validate new user">
<script>
//adding event handlers
document.querySelector('#createuser').onclick = create_user;
document.querySelector('#validateuser').onclick = validate_user;
function create_user()
{
//assign values for username and password
var username = document.querySelector("#txt_user").value;
var password = document.querySelector("#txt_password").value;
//using sessionstorage to keep user and password values
sessionStorage.setItem("username", username);
sessionStorage.setItem("password", password);
alert('new user is created');
}
function validate_user()
{
//getting previously recorded username and password
var recorded_username = sessionStorage.getItem("username");
var recorded_password = sessionStorage.getItem("password");
//assign values for username and password
var username = document.querySelector("#txt_user").value;
var password = document.querySelector("#txt_password").value;
//doing it as simple as possible, no filters (trim, lowercase) at all
if (username==recorded_username && password==recorded_password)
{alert('user and password are valid');}
else
{alert('validation error');}
}
</script>
Related
Below is html code for login form
<h2 class="title">Sign in</h2>
<div class="input-field">
<i class="fas fa-user"></i>
<input type="email" id="email" placeholder="Email"/>
</div>
<div class="input-field">
<i class="fas fa-lock"></i>
<input type="password" id="password" placeholder="New Password" />
</div>
<input type="submit" value="Login" class="btn solid" onclick="login()" />
Below is .js file code for login function
function login () {
alert('Login Function')
// Get all our input fields
email = document.getElementById('email').value
password = document.getElementById('password').value
// Validate input fields
if (validate_email(email) == false || validate_password(password) == false) {
alert('Email or Password is Outta Line!!')
return
// Don't continue running the code
}
auth.signInWithEmailAndPassword(email, password)
.then(function() {
// Declare user variable
var user = auth.currentUser
// Add this user to Firebase Database
var database_ref = database.ref()
// Create User data
var user_data = {
last_login : Date.now()
}
// Push to Firebase Database
database_ref.child('users/' + user.uid).update(user_data)
// DOne
alert('User Logged In!!')
})
.catch(function(error) {
// Firebase will use this to alert of its errors
var error_code = error.code
var error_message = error.message
alert(error_message)
})
}
everything is working fine but my web app is not connected to a database of firebase
Note I've already required library or dependencies whatever you want to call in both HTML and js files.
Currently in my registration form when the user enters different texts in the 'password' and 'confirm password' fields, he gets "passwords are not matching" on a new page.
Like this: https://i.stack.imgur.com/uXkyx.png
But I want to display an alert saying "Passwords are not matching". What changes should I make in my code to achieve this?
HTML code of registration form
<form action="/register" id="RegForm" method = "POST">
<input type="text" placeholder="Username" name="username">
<input type="email" placeholder="E-mail" name="email">
<input type="password" placeholder="Password" name="password">
<input type="password" placeholder="Confirm Password" name="confirmPassword">
<input type="submit" class="btn" value="Create account"/>
<a class="loginAnchor" href="/">Already a user? Sign up</a>
</form>
Express.js code
app.post("/register", async (req,res) =>{
try{
const password = req.body.password;
const cpassword = req.body.confirmPassword;
if(password === cpassword){
const registerEmployee = new Register({
username : req.body.username,
email : req.body.email,
password : password,
confirmPassword : cpassword
})
const registered = await registerEmployee.save();
res.status(201).render("login");
}
else{
//I want to display the message "Passwords not matching" in an alert.
res.send("Passwords are not matching");
}
}catch(error){
res.status(400).send(error);
}
})
I have this error message below despite setting the javascript in the html. The code below is my html code for registration but none of the javascript function or event listener are working. I am still learning about javascript and html so please advice on what I did wrong.
Error message
Uncaught ReferenceError: matchTest is not defined at HTMLInputElement.onkeyup
Register page
<div class="form">
<form id="register-form" action="#">
<ul class="form-container">
<li>
<h2>Create Account</h2>
</li>
<li>
<label for="name">Name</label>
<input type="name"
name="name"
id="name"
required />
</li>
<li>
<label for="email" class="emailBox">Email</label>
<input type="email"
name="email"
id="email"
required
/>
<span class="emailText"></span>
</li>
<li>
<label for="password" class="passBox">Password</label>
<input type="password"
id="password"
name="password"
class="password"
required
/>
<span class="passText"></span>
</li>
<li>
<label for="re-password">Re-Enter Password</label>
<input type="password"
id="re-password"
name="re-password"
class="re-password"
onkeyup="matchTest()"
required
/>
</li>
<li>
<button type="submit" class="primary">
Register
</button>
</li>
<li>
<div>Already have an account? Sign-In
</div>
</li>
</ul>
</form>
<script type="text/javascript">
window.onload = function() {
let email = document.getElementById("email")
let password = document.getElementById("password")
email.addEventListener('input',()=>{
let emailBox = document.querySelector('.emailBox')
let emailText = document.querySelector('.emailText')
const emailPattern = /[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{1,63}$/
if(email.value.match(emailPattern)){
emailBox.classList.add('valid')
emailBox.classList.remove('invalid')
emailText.innerHTML = "Your Email Address in Valid"
}else{
emailBox.classList.add('invalid')
emailBox.classList.remove('valid')
emailText.innerHTML = "Must be a valid email address."
}
})
password.addEventListener('input',()=>{
let passBox = document.querySelector('.passBox');
let passText = document.querySelector('.passText');
const passPattern = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}/;
if(password.value.match(passPattern)){
passBox.classList.add('valid');
passBox.classList.remove('invalid');
passText.innerHTML = "Your Password in Valid";
}else{
passBox.classList.add('invalid');
passBox.classList.remove('valid');
passText.innerHTML = "Your password must be at least 8 characters as well as contain at least one uppercase, one lowercase, and one number.";
}
})
function matchTest(){
let password = document.querySelector('password').value
let confirmPassword = document.querySelector('re-password').value
if(password != confirmPassword)
alert("Password don't match. Please try again.")
return false
}
else if(password == confirmPassword){
alert("Password match")
}
}
}
</script>
</div>
You need to change following things:
It is recommended to define addEventListener in JS not inline
repeatPassword.addEventListener("keyup", (e) => { matchTest(); });
Since you've defined the variable password, so it would be consistent to add repeatPassword also and get its value as password.value and reapatPassword.value in matchTest.
It is recommended to use === instead of ==.
I've used console.log in place of alert. Since you are checking for password equality then it's annoying to get alert after every key press.
window.onload = function() {
let email = document.getElementById("email");
let password = document.getElementById("password");
let repeatPassword = document.getElementById("re-password");
email.addEventListener("input", () => {
let emailBox = document.querySelector(".emailBox");
let emailText = document.querySelector(".emailText");
const emailPattern = /[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{1,63}$/;
if (email.value.match(emailPattern)) {
emailBox.classList.add("valid");
emailBox.classList.remove("invalid");
emailText.innerHTML = "Your Email Address in Valid";
} else {
emailBox.classList.add("invalid");
emailBox.classList.remove("valid");
emailText.innerHTML = "Must be a valid email address.";
}
});
password.addEventListener("input", () => {
let passBox = document.querySelector(".passBox");
let passText = document.querySelector(".passText");
const passPattern = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}/;
if (password.value.match(passPattern)) {
passBox.classList.add("valid");
passBox.classList.remove("invalid");
passText.innerHTML = "Your Password in Valid";
} else {
passBox.classList.add("invalid");
passBox.classList.remove("valid");
passText.innerHTML =
"Your password must be at least 8 characters as well as contain at least one uppercase, one lowercase, and one number.";
}
});
function matchTest() {
let pass = password.value;
let confirmPass = repeatPassword.value;
if (pass !== confirmPass) {
console.log("Password don't match. Please try again.");
return false;
} else {
console.log("Password match");
}
}
repeatPassword.addEventListener("keyup", (e) => {
matchTest();
});
};
<div class="form">
<form id="register-form" action="#">
<ul class="form-container">
<li>
<h2>Create Account</h2>
</li>
<li>
<label for="name">Name</label>
<input type="name" name="name" id="name" required />
</li>
<li>
<label for="email" class="emailBox">Email</label>
<input type="email" name="email" id="email" required />
<span class="emailText"></span>
</li>
<li>
<label for="password" class="passBox">Password</label>
<input type="password" id="password" name="password" class="password" required />
<span class="passText"></span>
</li>
<li>
<label for="re-password">Re-Enter Password</label>
<input type="password" id="re-password" name="re-password" class="re-password" required />
</li>
<li>
<button type="submit" class="primary">
Register
</button>
</li>
<li>
<div>Already have an account? Sign-In
</div>
</li>
</ul>
</form>
</div>
I am trying to make a login page using firebase, I am very new to this and have been reading through the firebase documentation to find a solution to my problem.
This is my function using the firebase.auth().signInWithEmailAndPassword() method from the firebase auth SDK.
function toggleSignIn() {
var email = document.getElementById('inputEmail').value;
var password = document.getElementById('inputPass').value;
if (email.length < 1) {
alert('Please enter an email address.');
return;
}
if (password.length < 1) {
alert('Please enter a password.');
return;
}
// Sign in with email and pass.
firebase.auth().signInWithEmailAndPassword(email, password).catch(function (error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
if (errorCode === 'auth/wrong-password') {
alert('Wrong password.');
} else {
alert(errorMessage);
}
console.log(error);
});
}
This will run once in a blue moon, but will stop running after that.
I click my 'Login_buton' on my HTML page, and it just clears the input email, and input password boxes.
Nothing happens after that, I check my console window and there is no user signed in.
This is what the HTML looks like
<div id="Login-google" class="input-group-google">
<button id="Logout_buton" type="submit" class="submit-buton" onclick="toggleSignOut()"> Test Logout </button>
</div>
<form id="Login" class="input-group">
<input id="inputEmail" type="text" class="input-field" placeholder="Email" required>
<input id="inputPass" type="text" class="input-field" placeholder="Password" required>
<input type="checkbox" class="check-box"> <span> Remember Password </span>
<button id="Login_buton" type="submit" class="submit-buton" onclick="toggleSignIn()"> Test Login </button>
</form>
Any help on this will be greatly appreciated, I am very new to this please be easy on me.
You are submitting a form, the default browser behaviour submits the form by making a POST request to the given URL. If you want to prevent the default behaviour you need to write e.preventDefault() in your submit method. Here is the updated code.
Use forms onsubmit event to submit the form
Javascript
function toggleSignIn(e) {
e.preventDefault(); // prevent the default behaviour
var email = document.getElementById('inputEmail').value;
var password = document.getElementById('inputPass').value;
if (email.length < 1) {
alert('Please enter an email address.');
return;
}
if (password.length < 1) {
alert('Please enter a password.');
return;
}
// Sign in with email and pass.
firebase.auth().signInWithEmailAndPassword(email, password).then((response) => {
console.log(response);
// do something when sign in is successful
}).catch(function (error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
if (errorCode === 'auth/wrong-password') {
alert('Wrong password.');
} else {
alert(errorMessage);
}
console.log(error);
});
}
HTML
<div id="Login-google" class="input-group-google">
<button id="Logout_buton" type="submit" class="submit-buton" onclick="toggleSignOut()"> Test Logout </button>
</div>
<form id="Login" class="input-group" onsubmit="return toggleSignIn(event)">
<input id="inputEmail" type="text" class="input-field" placeholder="Email" required>
<input id="inputPass" type="text" class="input-field" placeholder="Password" required>
<input type="checkbox" class="check-box"> <span> Remember Password </span>
<button id="Login_button" type="submit" class="submit-button"> Test Login </button>
</form>
</div>
I'm trying to make a simple registration and login function in Javascript. I want to have 6 input elements and 2 buttons in the html code.
(Login Section) 1 input for username, 1 for password and 1 button for running the login function.
(Registration section) 1 for new username, 1 for new email, one for new password , 1 for repeat password and 1 button for running the registration function.
First, a user fills in the registration fields, if a field is empty, alert "fill the field"s, else if new password is different from repet password, password and repet password dont match, else, alert you are registered. Here i want new password and new username to be saved in new password and use it in the login section.
Second, a user knows what the new password and new username is and can loggin.
if, username is logged in, alert you are in, else if username and password is the same as new username and new password, alert you are logged in, redirect to index.html.
This is what i have done so far.
var username = document.form.username.value;
var newusername = document.form.newusername.value;
var password = document.form.password.value;
var newpassword = document.form.newregpw.value;
var newregemail = document.form.newregemail.value;
var loggedin = "outside";
function login() {
if (loggedin == "inside") {
alert("You are already on the inside. Go shopping!");
} else if (username == newusername && password == newregpw) {
loggedin = "inside";
window.location = "index.html";
alert("Logged in, go shopping!");
} else {
alert("Wrong Username or Password. Try again.");
}
}
function reg() {
if (newusername === null || newregemail === null || newregpw === null || reppw === null) {
alert("Fill out all the fields.");
} else if (newregpw != reppw) {
alert("The password and repet password field dosen't match. Try again!");
} else {
alert("Congraulations you are now registerd");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/jquery-ui.min.js"></script>
<script src="script.js">
</script>
</head>
<body>
<div id="content">
<div id="navbar">
<ul>
<li>HOME
</li>
<li>ABOUT
</li>
<li>CONTACT
</li>
<li>ACCOUNT
</li>
<li>LOGIN
</li>
</ul>
</div> <a href="index.html">
<div id="header">
</div>
</a>
<div id="menu-clothes">
<ul>
<li class="menu-class">MEN
</li>
<li class="menu-class">WOMEN
</li>
<li class="menu-class">CHILDREN
</li>
</ul>
</div>
<div id="account">
<!-- Login och skapa ny medlem funktionen -->
<h4>Login/New account</h4>
<h5>Login</h5>
<h6>Usernamn/E-mail</h6>
<form name="login">
<input type="text" name="username" id="username" required/>
<h6>Password</h6>
<input type="password" name="password" id="password" required/>
<h6>Login</h6>
<input type="button" name="login" value="Login" id="login" onClick="login()" />
<h5>New Account</h5>
<h6>Choose Username</h6>
<input type="text" name="newusername" id="newusername" />
<h6>Enter E-mail</h6>
<input type="email" name="newregemail" id="newregemail" />
<h6>Choose Password</h6>
<input type="password" name="newpassword" id="newregpw" />
<h6>Repet Password</h6>
<input type="password" name="repetpassword" id="repregpw" />
<h6>Complete Registration</h6>
<input type="button" name="register" value="Register" id="register" onClick="reg()" />
</form>
</div>
<div id="footer">
<ul>
<li class="footer-class">HOME
</li>
<li class="footer-class">ABOUT
</li>
<li class="footer-class">CONTACT
</li>
</ul>
</div>
</div>
</body>
</html>
It seems like nothing is happening and i don't really understand why.
If you know any easier way of doing it or if you know what's wrong with the code i would appreciate it a lot!
Kind/Best Regards
Anton