Json Login with multiple user credentials - javascript

I am trying to do a login form by using JSON, below is my code:
<html>
<head>
<title> Login Form</title>
<script>
function validate(){
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var Userlist = [{"username":"asdf", "password":"123"}, {"username":"zxc", "password":"123"}]
var jobj = JSON.parse(Userlist);
for (var i=0; i < jobj.length; i++) {
if ( username == jobj.username && password == jobj.password)
{
alert ("Login successfully");
}
else{
alert("Invalid username and password");
}
}
}
</script>
</head>
<body>
<div class="container">
<div class="main">
<h2>Login Form</h2>
<form id="form_id" method="post" name="myform">
<label>User Name :</label>
<input type="text" placeholder="Enter username" name="username" id="username"/>
<label>Password :</label>
<input type="password" placeholder="Enter Password" name="password" id="password"/>
<input type="button" value="Login" id="submit" onclick="validate()"/>
</form>
</body>
</html>
I am unable to achieve this, when I enter with the given credentials nothing is appearing on the screen, Do I have to add some more functionality to achieve?

Working example
You don't need :
var jobj = JSON.parse(Userlist);
Just parse array like :
function validate()
{
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var Userlist = [{"username":"asdf", "password":"123"}, {"username":"zxc", "password":"123"}];
var logged = false;
for (var i=0; i < Userlist.length; i++) {
if ( username == Userlist[i].username && password == Userlist[i].password)
logged=true;
}
if(logged)
alert ("Login successfully");
else
alert("Invalid username and password");
}
Hope this helps.

Related

My JS function is not printing anything when two passwords does not matches

How can I make password field to check each other that the value written by user matches ?
function checkPassword(form) {
pOne = form.pOne.value;
pTwo = form.pTwo.value;
// If password not entered
if (pOne == '')
alert("Please enter Password");
// If confirm password not entered
else if (pTwo == '')
alert("Please enter confirm password");
// If Not same return False.
else if (pOne != pTwo) {
// alert ("\nPassword did not match: Please try again...")
document.querySelector(".submit").addEventListener("click", print)
function print() {
return document.querySelector(".pass").textContent = "Your password does not match!"
}
}
// If same return True.
else {
document.querySelector(".submit").addEventListener("click", print)
function print() {
return document.querySelector(".pass").textContent = "Your password match perfectly!"
}
}
}
<form class="formtwo" onsubmit="checkPassword(this)">
<input type="email" name="email" placeholder="Email"><br>
<input type="password" name="pOne" placeholder="Password">
<input type="password" name="pTwo" placeholder="Re-Type Password">
<p class="pass">djkakj</p>
<button type="submit" class="submit">Submit</button>
</form>
You need to add the event listener to the form submit before you test
window.addEventListener("load", function() {
document.getElementById("formtwo").addEventListener("submit", function(e) {
const pOne = this.pOne.value;
const pTwo = this.pTwo.value;
const pass = document.querySelector(".pass");
let errors = [];
// If password not entered
if (pOne == '') errors.push("Please enter Password");
if (pTwo == '') errors.push("Please enter confirm password");
if (pOne != pTwo) errors.push("Password did not match: Please try again...")
if (errors.length > 0) {
e.preventDefault(); // this will stop submission
alert(errors.join("\n"))
pass.textContent = "Your password does not match!"
return;
}
pass.textContent = "Your password match perfectly!"
})
})
<form id="formtwo">
<input type="email" name="email" placeholder="Email"><br>
<input type="password" name="pOne" placeholder="Password">
<input type="password" name="pTwo" placeholder="Re-Type Password">
<p class="pass">djkakj</p>
<button type="submit" class="submit">Submit</button>
</form>
You can check my solution. Hope it's easier to understand. There were some issues in your code.
If you want to prevent the form submit if the password doesn't match then you need to use event.preventDefault to prevent the default behaviour.
You can fire the submit event once and then check for your required values.
const form = document.querySelector('.formtwo');
form.addEventListener('submit', checkPassword);
function checkPassword(e) {
e.preventDefault();
let pOne = form.pOne.value;
let pTwo = form.pTwo.value;
// If password not entered
if (pOne == "") alert("Please enter Password");
// If confirm password not entered
else if (pTwo == "") alert("Please enter confirm password");
// If Not same return False.
else if (pOne != pTwo) {
document.querySelector(".pass").textContent =
"Your password does not match!";
}
// If same return True.
else {
document.querySelector(".pass").textContent =
"Your password match perfectly!";
// submitting form
form.submit();
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<form class="formtwo">
<input type="email" name="email" placeholder="Email"><br>
<input type="password" name="pOne" placeholder="Password">
<input type="password" name="pTwo" placeholder="Re-Type Password">
<p class="pass">Password matching status</p>
<button type="submit" class="submit">Submit</button>
</form>
</body>
</html>

Form Validation against an Array with JavaScript/ jQuery

I've seen a couple answers on Stack but none of them detail how exactly this works. Currently I have a simple form with username and password forms which works with predefined values but not working when values are in an array. I want to use JS to validate the forms that both password and username match data points as strings within the forms. My code below has no errors to my knowledge, but my logic statements don't fire a correct entry. How can I fix this? (I included jQuery because I know a little bit in that realm and if it helps I'll take it.)
<!DOCTYPE html>
<html>
<head>
<title>Coding Project</title>
</head>
<body style="font-family:Helvetica">
<h1>
Simple Login Form:
</h1>
<form>
<input type="text" id="username" placeholder="Enter username" value=""> <br> <br>
<input type="password" id="password" placeholder="Enter password" value=""> <br> <br>
<button type="button" onClick="mySubmit()"> Submit
</button>
</form>
<script type="text/javascript">
function mySubmit() {
var userNameInput = document.getElementById("username").value;
var passWordInput = document.getElementById("password").value;
var existingUserName = [["46179"], ["55678"]];
var existingPassWord = [["helloworld123"], ["helloworld456"]];
if (userNameInput == existingUserName && passWordInput == existingPassWord) {
alert("Correct Username");
} else if (userNameInput == "" && passWordInput == "") {
alert("Empty field, please enter Username and Password or Signup");
} else {
alert("Incorrect Username or Password");
}
}
</script>
</body>
</html>
I just corrected your condition, please check this: (If username and password both found in existing array then it will be triggered the warning "Incorrect Username or Password")
Note: If it's not fulfill your requirement, then please let me know.
<!DOCTYPE html>
<html>
<head>
<title>Coding Project</title>
</head>
<body style="font-family:Helvetica">
<h1>
Simple Login Form:
</h1>
<form>
<input type="text" id="username" placeholder="Enter username" value=""> <br> <br>
<input type="password" id="password" placeholder="Enter password" value=""> <br> <br>
<button type="button" onClick="mySubmit()"> Submit
</button>
</form>
<script type="text/javascript">
function mySubmit() {
var userNameInput = document.getElementById("username").value;
var passWordInput = document.getElementById("password").value;
var existingUserName = ["46179", "55678"];
var existingPassWord = ["helloworld123", "helloworld456"];
if (!existingUserName.includes(userNameInput) && !existingPassWord.includes(passWordInput)) {
alert("Correct Username");
} else if (userNameInput == "" && passWordInput == "") {
alert("Empty field, please enter Username and Password or Signup");
} else {
alert("Incorrect Username or Password");
}
}
</script>
</body>
</html>

alert not displaying in JS

alert is not working as expected! i don't know why...
I am trying to evaluate a form on client side. I have tried getElementsById, getElementsByName.
Where am i going wrong?
I am sure the flow of control goes through validate()
an alert statement immediately inside validate method is being displayed!
Here is my code:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" errorPage="Error.jsp"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript">
function validate() {
var uname = document.getElementById("uname").value;
var email = document.getElementById("email").value.indexof('#');
var pass = document.getElementById("pass").value;
var rpass = document.getElementById("rpass").value;
submitOK = true;
if (uname.length == 0) {
alert("Username cannot be empty")
submitOK = false;
}
if (email == -1) {
alert("Not a valid email");
submitOK = false;
}
if (pass.length === 0) {
alert("Password cannot be empty");
submitOK = false;
}
if (pass != rpass) {
alert("passwords don't match");
submitOK = false;
}
return submitOK;
}
</script>
<title>Register</title>
</head>
<body>
<h1>Register</h1>
<br />
<form action="RegInt.jsp" method="post" onsubmit="return validate()">
Enter UserName : <input type="text" name="uname" id="uname" value='${ param.uname}'placeholder="Enter Name" ><br/><br/>
Enter Email: <input type="email" name="email" id = "email" value='${param.email}'placeholder="Enter Email"><br/><br/>
Enter Password: <input type="password" name="pass" id = "pass" value='${param.pass}'placeholder="Enter password"><br/><br/>
Repeat Password: <input type="password" name="rpass" id = "rpass" value='${param.rpass}'placeholder="Repeat Password"/><br/>
<br/><br/>
<input type="submit"/>
</form>
<h4>${errorMsg}</h4>
</body>
</html>
Spelling of alret and indexOf !
getElementById is singular
submitOK="false" sets submitOK to true since a non-empty string is truthy. use submitOK=false
you did not return submitOK when you asked the question
function validate() {
var uname = document.getElementById("uname").value;
var email = document.getElementById("email").value.indexOf('#');
var pass = document.getElementById("pass").value;
var rpass = document.getElementById("rpass").value;
submitOK = true;
if (uname.length == 0) {
alert("Username cannot be empty")
submitOK = false;
}
if (email == -1) {
alert("Not a valid email");
submitOK = false;
}
if (pass.length === 0) {
alert("Password cannot be empty");
submitOK = false;
}
if (pass != rpass) {
alert("passwords don't match");
submitOK = false;
}
return submitOK;
}
<h1>Register</h1>
<br />
<form action="RegInt.jsp" method="post" onsubmit="return validate()">
Enter UserName :
<input type="text" name="uname" id="uname" value='${ param.uname}' placeholder="Enter Name">
<br/>
<br/>Enter Email:
<input type="email" name="email" id="email" value='${param.email}' placeholder="Enter Email">
<br/>
<br/>Enter Password:
<input type="password" name="pass" id="pass" value='${param.pass}' placeholder="Enter password">
<br/>
<br/>Repeat Password:
<input type="password" name="rpass" id="rpass" value='${param.rpass}' placeholder="Repeat Password" />
<br/>
<br/>
<br/>
<input type="submit" />
</form>
First check the spelling s and correct them. Then comment all the feilds and start troubleshooting them line by line. You will win. Regards !

Using JavaScript to validate form both onblur and when pressing submit

I'm trying to validate fields in a form using JavaScript. The fields should be validated either when the user leaves a field (onblur) and when the user presses submit. The form should not be sent if the validation fails in any way on a required field.
The thing is I also have a JS function that if validation succeeds, should rewrite one of the fields that is validated, and send the form.
This is my HTML:
<head>
<meta charset='UTF-8'>
<script type="text/javascript" src="./library/checkcreateuser.js"></script>
<script type="text/javascript" src="./library/hashcreateuser.js"></script>
</head>
<body>
<div class="maindiv">
<form name="createform" id="createform" onsubmit="return formhash();" action="#" method="post">
<input type="text" name="email" id="email" onblur="checkEmail()" placeholder="E-postadress" maxlength="50" />
<label for="email" id="labemail"></label><br />
<input type="text" name="testemail" id="testemail" onblur="checkEmailConfirm()" placeholder="Bekräfta e-postadress" maxlength="50" /><br />
<label for="testemail" id="labtestemail"></label><br />
<br />
... other input fields that should be validated, not yet written ...
<br />
<input type="password" name="password" id="password" placeholder="Lösenord" maxlength="50" /><br />
<label for="password" id="labpassword"></label><br />
<input type="password" name="testpassword" id="testpassword" placeholder="Bekräfta lösenord" maxlength="50" /><br />
<label for="testpassword" id="labtestpassword"></label><br />
<br />
<input type="submit" placeholder="Registrera" onclick="validateForm()"><br />
</form>
</div>
</body>
And this is my javascript for validation:
function checkEmail() {
var validemail = true;
var email = document.getElementById("email");
var divided = email.split("#");
var divlen = divided.length;
if (divlen != 2) {
validemail = false;
document.getElementById("labemail").innerHTML = "Felaktig e-postadress";
} else {
document.getElementById("labemail").innerHTML = "<font color='#00cc00'>Korrekt epostadress</font>";
}
// More code to validate Email to come
return validemail;
}
function checkEmailConfirm() {
var validtestemail = true;
var email = document.getElementById("email");
var testemail = document.getElementById("email");
if (testemail != email) validtestemail = false;
return validtestemail;
}
function validateForm() {
var validform = true;
var returnval = true;
validform = checkEmail();
if (validform == false) returnval = false;
validform = checkEmailConfirm();
if (validform == false) returnval = false;
return returnval;
}
My problem is that nothing happens when i leave the email- or testemail-fields.
My second question is, if I want the form not submitted if any of the validations fails, but submitted and also hashed using the function called formhash() if the validations succeeds, is this the correct way?
EDIT: Using the Chrome debugger, i have the following errors:
Uncaught TypeError: undefined is not a function: checkcreateuser.js:9
checkEmail: checkcreateuser.js:9
onblur: newuser.php:16
to check for the value entered in email and testemail you should use:
var email = document.getElementById("email").value;
var testemail = document.getElementById("testemail").value;// then use split on these values.
if you will use
var email = document.getElementById("email");//you will get error may be like split is not a function or something similar.

Validation is not working in second time button click

I am adding username and email to the userlist and validating email when adding. Validation is working when the page loads for the first time, If I tried to enter invalid email for second time and click the add button it is not working..
<form id="myform">
<h2>Add a User:</h2>
<input id="username" type="text" name="username" placeholder="name">
<input id="email" type="text" name="email" placeholder="email">
<button onclick='return addUser();' type="submit">add user</button>
</form>
<h2>UsersList:</h2>
<ul id="users"></ul>
<script type="text/javascript">
function addUser(){
var list = document.getElementById('users');
var username =document.getElementById('username').value;
var email = document.getElementById('email');
var entry = document.createElement('li');
if (email.value != '')
{
reg = /^[a-zA-Z0-9_.+-]+#[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/;
if (reg.test(email.value) == true) {
entry.appendChild(document.createTextNode(username + ' ' + email.value));
list.appendChild(entry);
return false;
}
else {
email.className += 'errorclass';
return false;
}
}
else{
alert("Please Enter Email Id");
return false;
}
}
</script>
<style>
.errorclass{
border:1px red solid;
}
</style>
Each time there is a validation error you add 'errorclass' to the email class. So the second time is "errorclasserrorclass" that is not defined in the css.
Use:
email.setAttribute('class','errorclass')

Categories

Resources