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
Related
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 do email validation after user type finish their email. However, it is not indicating that the email is valid or not. I place the javascript at the top to let it run while rendering but it doesn't work either. The code below is the screen for registration using javascript. This is rendered using nodejs. Is it due to the position of code or am I missing something?
RegisterScreen.js
const RegisterScreen = {
render: () =>
`
<script type="text/javascript">
const email = document.getElementById("email")
email.addEventListener('input',()=>{
const emailBox = document.querySelector('.emailBox')
const 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."
}
})
</script>
<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">Password</label>
<input type="password"
id="password"
name="password"
required
/>
</li>
<li>
<label for="re-password">Re-Enter Password</label>
<input type="password"
id="re-password"
name="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>`,
}
export default RegisterScreen
Your javascript is executing on HTML elements that don't yet exist. Load the javascript up after the page loads:
<script type="text/javascript">
window.onload = function() {
const email = document.getElementById("email")
email.addEventListener('blur',()=>{
const emailBox = document.querySelector('.emailBox')
const 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."
}
})
}
</script>
I am trying to display error/successful alert in the login panel. But sweet alert isn't displaying error/successful alert while first time writing wrong/correct password. I must to write one more time wrong password to showing sweet alert. I didn't understand why it is like this. I tried to inspect codes with breakpoint. In first time its going to Login.cshtml and although ViewBag.status is false its not going to if (ViewBag.status==false). Can someone help me?
Controller;
[HttpGet]
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(TBLUSER t)
{
var values = db.TBLUSER.FirstOrDefault(x => x.MAIL == t.MAIL && x.PASS == t.PASS);
bool status;
if (values != null)
{
FormsAuthentication.SetAuthCookie(values.MAIL, true);
status= true;
ViewBag.status = status;
Thread.Sleep(2500);
return RedirectToAction("Index", "Panel");
}
else
{
status = false;
ViewBag.status = status;
Thread.Sleep(2500);
return View();
}
}
View;
<div class="limiter">
<div class="container-login100">
<div class="wrap-login100 p-t-50 p-b-90">
<form class="login100-form validate-form flex-sb flex-w" method="post">
<span class="login100-form-title p-b-51">
LOGIN
</span>
<div class="wrap-input100 validate-input m-b-16" data-validate="Mail is required.">
<input class="input100" type="text" name="MAIL" placeholder="Mail">
<span class="focus-input100"></span>
</div>
<div class="wrap-input100 validate-input m-b-16" data-validate="Password is required.">
<input class="input100" type="password" name="SIFRE" placeholder="Password">
<span class="focus-input100"></span>
</div>
<div class="flex-sb-m w-full p-t-3 p-b-24">
<div class="contact100-form-checkbox">
<input class="input-checkbox100" id="ckb1" type="checkbox" name="remember-me">
<label class="label-checkbox100" for="ckb1">
Remember me
</label>
</div>
<div>
<a href="#" class="txt1">
Forgot pass?
</a>
</div>
</div>
<div class="container-login100-form-btn m-t-17">
<button class="login100-form-btn" id="btn1">
Login
</button>
#if (ViewBag.status == false)
{
<script>
$('#btn1').click(function () {
swal("Error", "Wrong password, please try again.", "error");
});
</script>
}
#if (ViewBag.status == true)
{
<script>
$('#btn1').click(function () {
swal("Information", "Successfully u have logged in.", "success");
});
</script>
}
</div>
<div style="margin-top:20px; margin-left:170px">
You dont have an acc? Create
</div>
</form>
</div>
</div>
</div>
I am trying to make a functional login and registration pages (I know that in real life I need to store the login info in a database but for now I would like to see my pages "working"). I created two pages with forms one for registration and one for login. I also have two JS files one for locally storing input values (registerDetails.js) and one for retrieving those values during login (login.js).
Storing the information is not a problem, however, when I try to log in with the information I have just inputted and know it's correct it still throws an "Error" at me to say that password and username don't match even though I know they do match.
SOLUTION IN THE COMMENTS - MIX UP OF VARIABLES
I even tried to error handle if there is a problem with browser compatibility, still to no avail.
This is HTML for register.html:
<form class="form-horizontal">
<fieldset>
<div id="legend">
<legend>
Register or <a class="login-link" href="login.html">Login</a>
</legend>
<p>All fileds marked with * are required.</p>
</div>
<hr />
<div class="control-group">
<!-- Username -->
<label class="control-label" for="username"><span class="asterisk">*</span> Username</label>
<div class="controls">
<input type="text" id="username" name="username" placeholder="Any letters or numbers without spaces"
class="input-xlarge" />
</div>
<br />
</div>
<div class="control-group">
<!-- E-mail -->
<label class="control-label" for="email"><span class="asterisk">*</span> E-mail</label>
<div class="controls">
<input type="text" id="email" name="email" placeholder="Enter your email here" class="input-xlarge" />
</div>
<br />
</div>
<div class="control-group">
<!-- Password-->
<label class="control-label" for="password"><span class="asterisk">*</span> Password</label>
<div class="controls">
<input type="password" id="password" name="password" placeholder="Password of atleast 4 characters"
class="input-xlarge" />
</div>
<br />
</div>
<div class="control-group">
<!-- Password -->
<label class="control-label" for="password_confirm"><span class="asterisk">*</span> Confirm Password</label>
<div class="controls">
<input type="password" id="password_confirm" name="password_confirm" placeholder="Please confirm password"
class="input-xlarge" />
</div>
<br />
</div>
<div class="control-group">
<!-- Button -->
<div class="controls">
<button type="submit" id="register" class="btn btn-success" onClick="store()">
Register
</button>
</div>
</div>
</fieldset>
</form>
Here is my HTML for login.html:
<form class="form-horizontal">
<fieldset>
<div id="legend">
<legend>
Login or <a class="login-link" href="register.html">Register</a>
</legend>
</div>
<hr />
<div class="control-group">
<!-- Username or Email-->
<label class="control-label" for="username">Username or Email</label>
<div class="controls">
<input type="text" id="usernameEmail" name="usernameEmail" placeholder="Enter your email or username"
class="input-xlarge" />
</div>
<br />
</div>
<div class="control-group">
<!-- Password-->
<label class="control-label" for="password">Password</label>
<div class="controls">
<input type="password" id="passwordLogin" name="password" placeholder="Enter your password"
class="input-xlarge" />
</div>
<br />
</div>
<div class="control-group">
<!-- Button -->
<div class="controls">
<button class="btn btn-success" type="submit" onclick="check()">Login</button>
</div>
</div>
</fieldset>
</form>
My registration JS works fine, the browser prompts me to save credentials for later use...
Which is here:
// Getting details from the registration form to later store their values
var userName = document.getElementById('username');
var userEmail = document.getElementById('email');
var password = document.getElementById('password');
var passwordConfirm = document.getElementById('password_confirm');
// Locally storing input value from register-form
function store() {
if (typeof (Storage) !== "undefined") {
localStorage.setItem('name', userName.value);
localStorage.setItem('email', userEmail.value);
localStorage.setItem('password', password.value);
localStorage.setItem('password_confirmation', passwordConfirm.value);
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}
}
My login page, however, throws the ERROR alert, even when I know for sure that the username and password match.
// check if stored data from register-form is equal to entered data in the login-form
function check() {
// stored data from the register-form
var storedName = localStorage.getItem('name');
// var storedEmail = localStorage.getItem('email');
var storedPassword = localStorage.getItem('password');
// entered data from the login-form
var userNameLogin = document.getElementById('usernameEmail');
var userPwLogin = document.getElementById('passwordLogin');
// check if stored data from register-form is equal to data from login form
if (userNameLogin.value == storedName && storedPassword.value == userPwLogin) {
alert('You are loged in.');
} else {
alert('ERROR.');
}
}
I have spent a few hours trying to rewrite the code to maybe see some typos or mistakes but I cannot find where I am going wrong! If anyone could help out as to show the reason why it does not match the username and password would be great.
It should alert me "You are logged in."
Thanks!
You have a typo
if (userNameLogin.value == storedName && storedPassword.value == userPwLogin) {
^^Here
}
Should be this instead
if (userNameLogin.value == storedName && userPwLogin.value == storedPassword ) {
}
By the way, your code will only log in with username (and not email) as it is. Don't forget to compare the email too.
Variables that are meant to store your elements at register page(userName, userEmail, etc.) might be null when store() is called.
I would suggest to get those inside the function:
function store() {
var userName = document.getElementById('username');
var userEmail = document.getElementById('email');
var password = document.getElementById('password');
var passwordConfirm = document.getElementById('password_confirm');
if (typeof (Storage) !== "undefined") {
localStorage.setItem('name', userName.value);
localStorage.setItem('email', userEmail.value);
localStorage.setItem('password', password.value);
localStorage.setItem('password_confirmation', passwordConfirm.value);
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}
}
But the solution lies in this line:
if (userNameLogin.value == storedName && storedPassword.value == userPwLogin)
In your case storedPassword doesn't have "value" and userPwLogin does, since userPwLogin is the element on your form
Your code isn't working right because you've mixed up your local storage variable with your input elements. This line:
if (userNameLogin.value === storedName && storedPassword.value === userPwLogin) {
it should be:
if (userNameLogin.value === storedName && userPwLogin.value === storedPassword) {
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>