How to check if a variable's value is in an array? - javascript

I made register and login options in an empty html (not on a webpage) just to see if I could and how I could do it. Now I ran into a problem - I can register multiple usernames that have the same value (for example I can register "test username" as many times as I want to).
I want to know how I can check if the value that the user puts in to register has already been registered.
Here is my code :
HTML :
<!-- Login -->
<div class="login">
<label>Login</label>
<input type="text" id="login-username" class="textbox" placeholder="Username"/>
<input type="password" id="login-password" class="textbox" placeholder="Password"/>
<button type="submit" onclick="login()">Login</button>
</div>
<!-- Register -->
<div class="register">
<label>Register</label>
<input type="text" id="register-username" class="textbox" placeholder="Username"/>
<input type="password" id="register-password" class="textbox" placeholder="Password"/>
<button type="submit" onclick="register()">Register</button>
</div>
JavaScript :
function login() {
if(document.getElementById("login-username").value == username1 && document.getElementById("login-password").value == password1) {
alert("Hi " + username1 + " you are now logged in.");
} else if(document.getElementById("login-username").value == username2 && document.getElementById("login-password").value == password2) {
alert("Hi " + username2 + " you are now logged in.");
} else {alert("Wrong username or password");}
function register() {
if (username1 == null && password1 == null) {
localStorage.removeItem("username1");
localStorage.setItem("username1", document.getElementById("register-username").value);
localStorage.removeItem("password1");
localStorage.setItem("password1", document.getElementById("register-password").value);
alert("Hi, " + document.getElementById("register-username").value + " is now registered.");
location.reload();
} else if (username2 == null && password2 == null) {
localStorage.removeItem("username2");
localStorage.setItem("username2", document.getElementById("register-username").value);
localStorage.removeItem("password2");
localStorage.setItem("password2", document.getElementById("register-password").value);
alert("Hi, " + document.getElementById("register-username").value + " is now registered.");
location.reload();
}
var username1 = localStorage.getItem("username1");
var username2 = localStorage.getItem("username2");
var usernameAlpha = [username1, username2]; //This is a list of all usernames
//and it's what I want to look through when I'm checking if the value/username already exists
var password1 = localStorage.getItem("password1");
var password2 = localStorage.getItem("password2");

try this
function register(){
var users = JSON.parse(localStorage.getItem('users')) || [];
var username = document.getElementById("register-username").value;
var password= document.getElementById("register-password").value;
var toBeRegister= true;
for(i=0;i<users.length;i++){
if(users[i].username === username){
toBeRegister = false
}
}
if(toBeRegister){
users.push({username:username,password:password})
localStorage.setItem('users', JSON.stringify(users));
}
}

Thanks to Rajesh I was able to make it work and here is how :
I just used his method to check if the username that the user typed in was in usernameAlpha. If it was I displayed an alert message "Username taken" and if it was not I simply registered the user like normal.
Here is the code :
function register() {
if(usernameAlpha.indexOf(document.getElementById("register-username").value) > -1) {alert("Username taken")
} else if (username1 == null && password1 == null && document.getElementById("register-username").value != "" && document.getElementById("register-password").value != "") {
localStorage.removeItem("username1");
localStorage.setItem("username1", document.getElementById("register-username").value);
localStorage.removeItem("password1");
localStorage.setItem("password1", document.getElementById("register-password").value);
alert("Hi, " + document.getElementById("register-username").value + " is now registered.");
location.reload();
} else if (username2 == null && password2 == null && document.getElementById("register-username").value != "" && document.getElementById("register-password").value != "") {
localStorage.removeItem("username2");
localStorage.setItem("username2", document.getElementById("register-username").value);
localStorage.removeItem("password2");
localStorage.setItem("password2", document.getElementById("register-password").value);
alert("Hi, " + document.getElementById("register-username").value + " is now registered.");
location.reload();
}
}

You mention 'array', but don't use them well. You still have variables username1 and username2, which means you have to copy a bunch of code (again) if you want to introduce username3. If you build an array of users, or an object where the username is the key/propertyname, then you can build a more dynamic user database.
You can save and load the entire object in a serialized way to and from localStorage.
Do note that although it's a fun exercise, localStorage is not a safe place for this, and storing passwords (either in plain text or encrypted) is not a good practice either.
Anyway, it could look something like this:
var
userDatabase = null;
function loadUserDatabase() {
// Load the user database only if it wasn't loaded yet. This way, various functions can
// always call this function 'to be sure'.
if (userDatabase === null)
userDatabase = JSON.parse(localStorage.getItem("userDatabase"));
}
function saveUserDatabase() {
// Save the entire database back to local storage.
localStorage.setItem("userDatabase", JSON.stringify(userDatabase));
}
function normalizeUsername(username) {
// "Normalize" the username by converting different styles of writing to
// a base form.
// In this case, trim and convert to lowercase to effectively make user
// names case insensitive while still usings keys/properties.
return username.trim().toLowerCase();
}
function findUser(username) {
// Check if user database is loaded
loadUserDatabase();
// Find the user by username.
username = normalizeUsername(username);
if (userDatabase.hasOwnProperty(username)) {
return userDatabase[username];
}
return false;
}
function isValidUsername(username) {
// Implement any limits you want (or need) to impose here.
// A length check of, say <1000 would be a nice addition.
return username != '';
}
function setUser(username, password) {
loadUserDatabase();
username = normalizeUsername(username);
// Set/overwrite the user
userDatabase[username] = {password: password};
// Save the database to disk.
saveUserDatabase();
}
function login() {
var username = document.getElementById("login-username").value;
var password = document.getElementById("login-password").value;
if (user = findUser(username)) {
if (user.password == password) {
// There is a match, log in
alert('login successful as user ' + username);
} else {
// Password incorrect
alert('Invalid password for username ' + username);
}
} else {
// User not found
alert('User ' + username + ' not found');
}
}
function register() {
var username = document.getElementById("register-username").value;
var password = document.getElementById("register-password").value;
if (!isValidUsername(username)) {
alert('invalid username')
} else if (user = findUser(username)) {
alert('user ' + username + ' already exists');
} else {
setUser(username, password);
alert('user ' + username + ' created');
}
}
<!-- Login -->
<div class="login">
<label>Login</label>
<input type="text" id="login-username" class="textbox" placeholder="Username"/>
<input type="password" id="login-password" class="textbox" placeholder="Password"/>
<button type="submit" onclick="login()">Login</button>
</div>
<!-- Register -->
<div class="register">
<label>Register</label>
<input type="text" id="register-username" class="textbox" placeholder="Username"/>
<input type="password" id="register-password" class="textbox" placeholder="Password"/>
<button type="submit" onclick="register()">Register</button>
</div>

use the toString method from Object.prototype.
if( Object.prototype.toString.call( Variable ) === '[object Array]' ) {
alert( 'Array!' );
}

Related

Replace/Split usage in StreetAddress field Javascript

I am trying to make a simple string manipulation program, but I am running into problems.
WHAT THE PROGRAM SHOULD DO:
enteredname field must have at least one space but not in the first position.
enteredname field must contain 'miller' in anycase somewhere.
State field must be only two characters long.
Zip field must start with '45'
Lastly, streetaddress field is not required to contain the word street, but if it does, it is to be changed to 'Street'.
NOT WORKING:
Currently, everything works except the 'street' name check.
ERROR LOCATION:
if (streetaddress.toLowerCase().indexOf("street") == -1)
Current code:
//need to initialize to empty strings
var enteredname = "";
var streetaddress = "";
var city = "";
var state = "";
var zip = "";
function ValidateandDisplay() {
enteredname = document.getElementById("NameTextBox").value;
streetaddress = document.getElementById("StreetAddressTextBox").value;
city = document.getElementById("CityTextBox").value;
state = document.getElementById("StateTextBox").value;
zip = document.getElementById("ZipTextBox").value;
var isValid = CheckEntries(); // call isValid function here that will
// perform all validation and return with a true or false from CheckEntries
if (isValid) {
//string to display
var correctentries = enteredname + "<br/>" +
streetaddress + "<br/>" + city + ", " + state + " " + zip;
document.getElementById("AddressDiv").innerHTML = correctentries;
}
}
function CheckEntries() {
//perform all checks here
//use separate ifs to determine each validation requirement
// alerting the user to the particular problem if something didn't
// pass validation and returning with a false
// ALL of your validation MUST be above the return true statement below
// it will only get to THIS return if all validation (conditions) were ok
if (enteredname[0] == ' ')
{
alert("First position in name field can not be a space.")
return false;
}
if (enteredname.indexOf(" ") == -1)
{
alert("no spaces found in entry.")
return false;
}
if (enteredname.toLowerCase().indexOf("miller") == -1)
{
alert("miller is not in name field.")
return false;
}
if (state.length != 2)
{
alert("State field must be only two characters long.")
return false;
}
if (zip[0] != '4' || zip[1] != '5')
{
alert("Zip field must start with 45.")
return false;
}
if (streetaddress.toLowerCase().indexOf("street") == -1)
{
streetaddress.replace("street", "Street");
return true;
}
else
return true;
}
Name: <input id="NameTextBox" type="text" /> FirstName LastName with a space between<br /> Street Address: <input id="StreetAddressTextBox" type="text" /> <br /> City: <input id="CityTextBox" type="text" /> <br /> State: <input id="StateTextBox" type="text"
/> <br /> Zip: <input id="ZipTextBox" type="text" /> <br />
<input id="Button1" type="button" value="Validate Entries" onclick="ValidateandDisplay()" />
<div id="AddressDiv">If entered correctly, your address will display here.</div>
<input id="Button1" type="button" value="Split a String" onclick="SplitThis()" />
String (array) indices start at 0
state.length > 2 ==> shoulf be "not equal"
(zip[-1] != '4' && zip[0] != '5') => It must be OR. And the indices are wrong
You are missing quotes in last if statement

How to prevent users from easily accessing localStorage

I am creating a login/signup form for my html blog website. I've managed to create the user information using localStorage or sessionStorage. I would store it whenever someone creates an account, and get it whenever someone wants to log in.
I haven't made the sign out or actual user page yet, but that is not my problem. The problem is that it is too easy for someone to steal passwords or clear all the account data using localStorage.clear()
Here is an HTML example:
<html>
<head>
<script src="index.js"></script>
<link rel="stylesheet" href="style.css">
<title>Accounts</title>
</head>
<body>
<article>
<h1>Log In</h1>
<input type="text" id="signin-username" placeholder="Username" value="">
<input type="password" id="signin-password" placeholder="Password" value="">
<button type="submit" onclick="signin()">Sign In</button>
<!------------------------------------>
<h1>Create Account</h1>
<input type="text" id="create-username" placeholder="Username" value="">
<input type="password" id="create-password" placeholder="Password" value="">
<button type="submit" onclick="create()">Create Account</button>
</article>
</body>
</html>
And here is the javascript for it:
var a = localStorage.length;
function signin() {
var name = document.getElementById('signin-username').value;
var pass = document.getElementById('signin-password').value;
if (name === '' && pass === '') {
console.log('Please provide your account details')
}
else if (name === '') {
console.log('Please provide your username!');
}
else if (pass === '') {
console.log('Please provide your password!');
}
else {
var ii;
for (ii = 0; ii < a; ii++) {
if (name === localStorage.key(ii)) {
console.log('Logged in as ' + name);
ii > a
}
else {
console.log('Account Does Not Exist!')
}
}
}
};
function create() {
var username = document.getElementById('create-username').value;
var password = document.getElementById('create-password').value;
if (username === '' && password === '') {
console.log('Invalid Username and Password')
}
else if (username === '') {
console.log('Invalid Username');
}
else if (password === '') {
console.log('Invalid Password');
}
else {
var i;
for (i = 0; i < a; i++) {
if (username === localStorage.key(i)) {
console.log('Username Exists!');
}
else {
localStorage.setItem(username, password)
}
};
}
}
I had to post The Full thing in order for it to make sense.
Anyone have suggestions, like user cookies, for storing data?
You can even redirect me to a login example!
I've managed to create the user information using localStorage or sessionStorage.
LocalStorage is "local" to the web browser. Data stored in LocalStorage is not shared with the web server, or with other web browsers viewing the site. It makes no sense to store account data in these locations, because doing so will result in an "account" that only exists on one computer.
(SessionStorage works similarly, except it disappears when the browser is closed -- so it's even less useful for your purposes.)
If you want to allow users to create accounts on your web site, you will need some sort of code running on the web server to implement these accounts. There is no way to implement this functionality entirely in client-side Javascript.

Using HTML WebStorage to have multiple username and passwords

I am using WebStorage to make a simple login system with username/password. (I don't know if this is the best way.)
It is working, but the problem is, it only works with one username and password. How do I make it so that it can store multiple usernames/passwords? Or perhaps I should be using a different system to do this?
Code:
<html>
<head>
</head>
<body>
<input type="text" placeholder="input username here" id="textbox">
<input type="text" placeholder="input password here" id="textbox2">
<input type="button" value="sign up" onclick="signup()">
<br>
<input type="text" placeholder="input username here" id="textbox3">
<input type="text" placeholder="input password here" id="textbox4">
<input type="button" value="login" onclick="login()">
<p id="result"></p>
<br>
<br>
<div id="settings">
<h1>Settings</h1>
<br>
<input type="text" placeholder="background color" id="bgc">
<br>
<input type="button" onclick="changeSettings()" value="Change settings">
</div>
<script>
function changeSettings() {
if(loggedIn == true) {
if(typeof(Storage)!= "undefined") {
var backg = document.getElementById("bgc").value;
if(backg!="") {
localStorage.setItem("backgroundColor", backg);
document.body.style.background = localStorage.getItem("backgroundColor");
} else {
alert("Enter a color.")
}
} else {
alert("No support.")
}
} else {
alert("You must be logged in to do that.")
}
}
function loadSettings() {
if(typeof(Storage)!="undefined") {
document.body.style.background = localStorage.getItem("backgroundColor");
} else {
alert("No support.")
}
}
function signup() {
if(typeof(Storage)!= "undefined") {
var username = document.getElementById("textbox").value;
var password = document.getElementById("textbox2").value;
if(username!="" && password!="") {
localStorage.setItem("username", username);
localStorage.setItem("password", password);
} else {
alert("Please enter a valid username and password.")
}
} else {
alert("No support.")
}
}
function login() {
if(typeof(Storage)!= "undefined") {
var username = localStorage.getItem("username");
var password = localStorage.getItem("password");
var usernameInput = document.getElementById("textbox3").value;
var passwordInput = document.getElementById("textbox4").value;
if(usernameInput!="" && passwordInput!="") {
if(usernameInput == username && passwordInput == password) {
document.getElementById("result").innerHTML = "Logged in!";
loggedIn = true;
loadSettings();
} else {
document.getElementById("result").innerHTML = "Wrong password/username!";
}
} else {
alert("Please enter a valid username and password.")
}
} else {
alert("No support.")
}
}
</script>
</body>
</html>
ps: sorry if it's messy :p
You should probably be using SQL if you want to store user inputs such as Usernames and Passwords.
Hashing & Password Storage
Good video to watch if your trying to learn Databases!
:)
Not a good way to store the plain username/password in localStorage. anyone can change those value. Since you check the login using
localStorage.setItem("username", username);
localStorage.setItem("password", password);
var username = localStorage.getItem("username");
var password = localStorage.getItem("password");
usernameInput == username && passwordInput == password
This login condition can make true using different ways.
Found this article from the Google, Hope you'll get some idea to do in
secure way :)

Check if username already exists in SQLite using JavaScript

I am new to JavaScript and am making a restaurant app which consists of a registration form. I want to check if the username already exists and if it does exist it should throw an alert to the user on button click.
JavaScript code:
<script type="text/javascript">
var db;
var shortname="R_loginDB";
var version = "1.0";
var displayName = "R_loginDB";
var maxSize = 90000;
function onBodyLoad() {
db = openDatabase(shortname,version,displayName,maxSize);
db.transaction(function(tx){
tx.executeSql('CREATE TABLE IF NOT EXISTS R(UserName TEXT NOT NULL PRIMARY KEY,Password TEXT NOT NULL,ConPassword TEXT NOT NULL)');
});
}
function ListDBValues() {
if (!window.openDatabase) {
alert('Databases are not supported in this browser.');
return;
}
$('#output').html('');
db.transaction(function(transaction) {
transaction.executeSql('SELECT * FROM R;', [], function(transaction, result) {
if (result != null && result.rows != null) {
for (var i = 0; i < result.rows.length; i++) {
var row = result.rows.item(i);
$('#output').append('<br>' + ' ' + row.UserName+ ' ' + row.Password + ' '+ row.ConPassword);
}
}
});
});
return;
}
ListDBValues();
function AddValues() {
var flag = false;
if ($("#pass").val() != $("#conpass").val()) {
alert("Passwords do not match.");
window.location.href = "r_register.html";
} else if (flag == false) {
try {
db.transaction(function(transaction) {
transaction.executeSql('INSERT INTO R(UserName, Password, ConPassword) VALUES (?,?,?)',[$('#uname').val(),$('#pass').val(),$('#conpass').val()]);
});
flag = true;
window.location.href = "login.html";
} catch(err) {
alert("Username " + $("#uname").val() + " is already taken!! Please chose another one");
window.location.href = "r_register.html";
}
}
}
AddValues();
</script>
HTML code:
<body onload="onBodyLoad()">
<div id="main">
<img id="bg" src="file:///android_asset/www/images/bigtable_1_blur.jpg"/>
<input id="uname" type="text" placeholder=" Username"></input>
<input id="pass" type="password" placeholder=" Password"></input>
<input id="conpass" type="password" placeholder=" Confirm Password"></input>
<p id="login"><b>Already have an account?<i><u>Login</u></i></b></p>
<!-- <a href="second.html"> -->
<input id="btn" type="button" value="Register" onclick="AddValues()"></input><br/>
<!-- </a> -->
<input id="btn2" type="button" value="show" onclick="ListDBValues()"/></input>
<span id="output"></span>
</div>
</body>
WebSQL API is depricated. It is unlikely to ever be supported on platforms that don't currently support it, and it may be removed from platforms that do.
Try using localStorage instead. Check out more at Cordova storage documentation

Remove form error with correct input

I just made a registration form which will tell you in red(CSS) letters if something is wrong. However I want this text to go away as soon as the user writes it correctly. How do I do that?
<script>
function validateForm2() {
var usrnm2 = document.getElementById("usrnm2").value;
var passw2 = document.getElementById("passw2").value;
var cnfpassw2 = document.getElementById("cnfpassw2").value;
var age = document.getElementById("age").value;
if (usrnm2 == null || usrnm2 == "") {
document.getElementById("error1").innerHTML = "You must enter a username";
return false;
}
else if (passw2 == null || passw2 == "") {
document.getElementById("error2").innerHTML = "You must enter a password";
return false;
}
else if (cnfpassw2 !== passw2) {
document.getElementById("error3").innerHTML = "Password does not match";
return false;
}
else if (age < 18) {
document.getElementById("error4").innerHTML = "You are not old enough to enter this site"
return false;
}
else {
alert("Congratulations, you have registered successfully!")
}
}
</script>
<script>
function register2() {
validateForm2()
}
</script>
<form>
Username:
<input id="usrnm2" type="text" name="username"><p id="error1"></p>
Password
<input id="passw2" type="password" name="password"><p id="error2"></p>
Confirm Password
<input id="cnfpassw2" type="password" name="confirmpw2"><p id="error3"></p>
Age
<input id="age" type="number" name="age"><p id="error4"></p><br />
<input id="bttn2" type="button" value="Register!" onclick="register2()"><br />
</form>
Separate the validation conditions into single block if statements, and then include a handler for returning the fields to normal when they are entered correctly:
if (field is entered incorrectly) {
document.getElementById("error").innerHTML = "You must enter correctly";
return false;
}
else {
document.getElementById("error").innerHTML = "";
}
...
alert("Congratulations, you have registered successfully!");
You simply need to place the alert after all of the statements - it will execute as long as none of the conditions fail and thus return.

Categories