I am having issues searching in an array of objects. Basically what my page needs to do is to create a new "client" using information entered by me, such as Full name, User name, Email and Password. Each one of these clients are objects in an array as you can see below.
var clientlist = [{"username":"John","fullname":"John Doe",
"email":"john.doe#hotmail.com","type":"client","password":"jdoe2"},
This client is already created in my js file, what I need to do is to create a new object to add to this array with this same structure. For example,
var clientlist = [{"username":"Peter","fullname":"Peter Jones",
"email":"peter.jones#hotmail.com","type":"client","password":"pjones1"},
I have written the code but it doesn't work properly, I cannot seem to search for the username to see if the username that I am adding already exists, it may be a syntax mistake. I will leave my complete code below and thanks in advance for the assistance!.
var clientlist = [{"username":"John","fullname":"John Doe",
"email":"john.doe#hotmail.com","type":"client","password":"jdoe2"},
var Client = {};
function NewClient(){
var found;
var user = $("#username").val();
for (var i = 0; i < clientlist.length; i++) {
if (clientlist[i] == user) {
found = true;
}else{
found = false;
}
}
if (found == true){
$("#msj").html("User already exists!");
}
else if(found == false){
Client["fullname"] = $("#fullname").val();
Client["username"] = user;
Client["email"] = $("#email").val();
Client["type"] = "client";
Client["password"] = $("#password").val();
clientlist[clientlist.length] = Client;
$("#msj").html("New client has been created");
}
}
Several problems with your for loop.
for (var i = 0; i < clientlist.length; i++) {
if (clientlist[i] == user) {
found = true;
}else{
found = false;
}
So what are we working with? clientlist is array so clientlist[i] is an element of that array...which happens to be an object.
user value is a string so there is no way to equate a string to object in the if.
Correction there would be to inspect the correct property value in object:
if (clientlist[i].username == user) {
Next problem is that the loop keeps going even if a match is found. As loop continues found will be updated for each iteration. Thus found will only be set based on the very last object in array regardless if a match was already determined.
To correct this could put that for loop in a function so it breaks the loop by returning true if match is found. Alternative would be use other array methods like Array.prototype.some() which returns a boolean based on conditional in callback. Or use break if a match is found to prevent loop continuing.
break will be simplest to plugin to the code so final would be
for (var i = 0; i < clientlist.length; i++) {
if (clientlist[i].username == user) {
found = true;
break;// quit loop since we found a match
}else{
found = false;
}
You need to change this
for (var i = 0; i < clientlist.length; i++) {
if (clientlist[i] == user) {
found = true;
}else{
found = false;
}
}
to
var found = false;
for (var i = 0; i < clientlist.length; i++) {
if (clientlist[i].username == user) {
found = true;
break;
}
}
You can use Array#some for this: It lets you run a callback against each entry in an array and determine if it matches a condition. some stops and returns true the first time you return a truthy value from the callback, or returns false if no calls to the callback return a truthy value.
So:
if (clientlist.some(function(entry) { return entry.username === user; })) {
$("#msj").html("User already exists");
} else {
// ...add the user...
}
That's more concise with ES2015+ arrow functions:
if (clientlist.some(entry => entry.username === user)) {
$("#msj").html("User already exists");
} else {
// ...add the user...
}
Also note that you don't want to reuse the same Client object each time, because on the next add, you'll just change the existing object's properties. Instead, create a new object each time:
clientlist.push({
username: user,
fullname: $("#fullname").val(),
email: $("#email").val(),
type: "client",
password: $("#password").val()
});
var clientlist = [{"username":"John","fullname":"John Doe",
"email":"john.doe#hotmail.com","type":"client","password":"jdoe2"}];
function NewClient() {
var user = $("#username").val();
if (clientlist.some(function(entry) { return entry.username === user; })) {
$("#msj").html("User already exists");
} else {
clientlist.push({
username: user,
fullname: $("#fullname").val(),
email: $("#email").val(),
type: "client",
password: $("#password").val()
});
$("#username, #fullname, #email, #password").val("");
$("#msj").html("New client has been created");
}
}
$("#btn").on("click", NewClient);
<div>
<label>
Username: <input type="text" id="username">
</label>
</div>
<div>
<label>
Fullname: <input type="text" id="fullname">
</label>
</div>
<div>
<label>
Email: <input type="text" id="email">
</label>
</div>
<div>
<label>
Password: <input type="password" id="password">
</label>
</div>
<div><input type="button" id="btn" value="Add"></div>
<div id="msj"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Related
I have two arrays in JavaScript. One contains usernames and one contains passwords. I want to create a loop that checks what position (i) the username is in - in the 'approvedUsernames' array - that was inputted by the user, and takes that same 'i' value in the 'approvedPasswords' array and picks the value that was found. then compare the two. If they match, a successful login happens, if not it is unsuccessful
Please see existing Arrays and the code i have already written below
any help greatly appreciated
i hope this was clear enough i had trouble wording it :)
James
EDIT: I KNOW THIS IS A VERY INSECURE WAY TO STORE PASSWORDS IT IS JUST TEMPORARY TO TEST THE LOGIN ALGORITHM. THE FINAL VERSION WILL DEFINITELY BE USING PHP+SQL DATABASE
Arrays:
approvedLogins = ['JamesLiverton', 'SamW'] approvedPasswords = ['password', 'coding']
Code:
function login(){
var username = document.getElementById('usernameField').value
var password = document.getElementById('passwordField').value
for (i = 0; i < approvedLogins.length; i++) {
if (username == approvedLogins[i].username && password == approvedPasswords[i].password) {
alert('Login Sucessful')
return
}
else {
alert('Login Unsucessful')
return
}
}
}
First, if you're planning on doing this, I have a feeling that you don't know much about security. I suggest you look into third party authentication (which, if you're asking this kind of question, might be out of your skill level, but still). At the very least, consider encrypting your user's password, with a salt (look up what a salt is).
With that said, you can do this.
function login() {
const username = document.getElementById('usernameField').value
const password = document.getElementById('passwordField').value
alert(isValidLogin(username, password) ? 'Login successful' : 'Login failed')
}
// create a separate function for checking validity, so it's easier
// to refactor/reimplement later, if need be.
function isValidLogin(username, password) {
const usernameArray = ['name1', 'name2', ... 'nameN']
const passwordArray = ['pw1', 'pw2', ... 'pwN']
const usernameIndex = usernameArray.findIndex(item => item === username)
return usernameIndex !== -1 && passwordArray[usernameIndex] === password
}
let approvedLogins = ['JamesLiverton', 'SamW']
let approvedPasswords = ['password', 'coding']
function login(){
var username = document.getElementById('usernameField').value
var password = document.getElementById('passwordField').value
let index = approvedLogins.indexOf(username)
if (password === approvedPasswords[index]) {
alert('Login Sucessful')
} else {
alert('Login Unsucessful')
}
}
<input type="text" id="usernameField" placeholder="username" /><input type="text" id="passwordField" placeholder="password" />
<button onclick="login()">login</button>
Check this example:
var approvedLogins = ['JamesLiverton', 'SamW'];
var approvedPasswords = ['password', 'coding'];
function login(username) {
if (approvedLogins.includes(username)) {
var matchedPassword = approvedPasswords[approvedLogins.indexOf(username)];
console.log(matchedPassword);
} else {
console.log("Username not found in array!");
}
}
It checks if the Username provided in the login() parameter, is found in the array. If it's inside the array, then it gets the password relative to the position of the username within that array. For example, "SamW" would be "coding".
I hope this helps.
I have two functions created already (isEmailValid & isPasswordValid) below which I could use some feedback on as well.I'm supposed to have them return a boolean value (if they follow the correct format). This would then get passed on to the Validator function which is supposed to analyze a loadData function with entries in LocalStorage to see if the email/password combo matches.
Email & Password Functions:
function isEmailValid(email) {
var res1;
var emailText = document.email.value;
var pattern = /^[a-zA-Z0-9\-_]+(\.[a-zA-Z0-9\-_]+)*#[a-z0-9]+(\-[a-z0-9]+)*(\.[a-z0-9]+(\-[a-z0-9]+)*)*\.[a-z]{2,4}$/;
if (pattern.test(emailText))
{
res1 = "TRUE";
} else {
res1 = "FALSE";
}
}
function isPasswordValid(passwd) {
var res2;
var str = document.passwd.value;
if (str.match(/[a-z]/g) && str.match(/[A-Z]/g) && str.match(/[0-9]/g) && str.match(/[^a-zA-Z\d]/g) && str.length >= 8)
res2 = "TRUE";
else
res2 = "FALSE";
}
loadData function
function loadData()
{
var coordinators = [
{
email: "jjd#gmail.com",
firstName: "Jennifer",
lastname: "Davis",
role: "instructor",
password:"anoth3rpass"
},
{
email: "boss_man#yahoo.com",
firstName: "Anderson",
surname: "Alleyne",
role: "instructor",
password:"passw0rd"
}
]
var students = [
{
year: "2018",
student_id: "220249309",
firstName: "Merissa",
lastName: "Halliwall",
email: "mm_h#hotmail.com",
password:"f1rstpa55",
address: "Lodge Road Ch Ch"
},
{
year: "2020",
student_id: "408306622",
firstName: "Vanda",
lastName: "Marshall",
email: "vmarhsall#guardian.co.uk",
password:"oll1p0ps",
address: "Sargeants Village Tenantry Ch Ch"
},
{
year: "2019",
student_id: "210350493",
firstName: "Mark",
lastName: "Belgrave",
email: "bboy89#hotmail.com",
password:"246bajan",
address: "76 Edghill Terrace"
},
{
year: "2020",
student_id: "200006059",
firstName: "Pamale",
lastName: "Gaskin",
email: "pamgask99#gmail.com",
password:"pamal3gask",
address: "Lot 33 The Belle"
}
}
//add to localStorage
if(!localStorage.getItem("coordinators"))
{
localStorage.setItem("coordinators", JSON.stringify(coordinators));
}
if(!localStorage.getItem("students"))
{
localStorage.setItem("students", JSON.stringify(students));
}
}
There are coordinators (admins) and students. I'm supposed to have the login page take you to different sites depending on which you are.
I am just a bit lost on how to create the Validator function...
What I understood from you question is if email validation and password validation is successful then you want to do some action otherwise another. I have written a simple code that may help you to structure you code.
var emailValidate = function() {
var x = 1;
if (x === 2) {
return true;
} else {
return false;
}
};
var passValidate = function() {
var y = 1;
if (y === 1) {
return true;
} else {
return false;
}
};
function allValidate() {
var isEmailValidate = emailValidate();
var isPassValidate = passValidate();
if (isEmailValidate && isPassValidate) {
console.log("Pass");
} else {
console.log("Fail");
}
}
allValidate();
Note: I see it's for an assignment. But here are some disclaimers:
Never do this in the real world, this is not secure at all. User credentials should never be exposed client-side (in JS). They should be checked server-side.
Your password validation function requires passwords to have at least a lower case letter, an upper case letter, a number, no special characters, and have a length of 8 at minimum. But in your example users, none of them respect that rule (no uppercase). So that won't work.
Here are things I noticed:
First, you need to fix your two validator functions, which don't return anything. You're creating res1 and res2 variables, but not doing anything with them?
Instead of returning Strings ("TRUE" and "FALSE"), you should use Booleans (true or false).
Taking the above tips into account, you can simplify this kind of code:
if (x) { return true; } else { return false; }
into:
return x; // Much shorter, isn't it?
You're declaring email and passwd parameters for your functions, but you're not using them. You'll have better control over the reusability of your code if you extract the knowledge of the DOM (HTML) from them. Pass Strings, and just use those Strings.
Your isValidPassword uses match, which either returns an Array or null. For your purpose, it would make more sense to use test, which returns a Boolean.
In Regex (Regular expression), to check for the presence of a single character, you don't need the g flag (global)
This regex: /[^a-zA-Z\d]/, and especially the [^ part means that the password should not contain any character present between those brackets. Here is a version which would make more sense: /^[a-zA-Z\d]+$/. It requires that between the beginning (^) and the end ($), there should be one or more (+) of only those characters.
If I take all of this into account, this is how I would do it (you can try it using the blue button below):
// Minified in this example, for clarity
var coordinators = [{email:"jjd#gmail.com",firstName:"Jennifer",lastname:"Davis",role:"instructor",password:"anoth3rpass"},{email:"boss_man#yahoo.com",firstName:"Anderson",surname:"Alleyne",role:"instructor",password:"passw0rd"}];
var students = [{year:"2018",student_id:"220249309",firstName:"Merissa",lastName:"Halliwall",email:"mm_h#hotmail.com",password:"f1rstpa55",address:"Lodge Road Ch Ch"},{year:"2020",student_id:"408306622",firstName:"Vanda",lastName:"Marshall",email:"vmarhsall#guardian.co.uk",password:"oll1p0ps",address:"Sargeants Village Tenantry Ch Ch"},{year:"2019",student_id:"210350493",firstName:"Mark",lastName:"Belgrave",email:"bboy89#hotmail.com",password:"246bajan",address:"76 Edghill Terrace"},{year:"2020",student_id:"200006059",firstName:"Pamale",lastName:"Gaskin",email:"pamgask99#gmail.com",password:"pamal3gask",address:"Lot 33 The Belle"},{year:"2020",student_id:"200006060",firstName:"Mayas",lastName:"Knaizeh",email:"mayas.k#gmail.com",password:"Mayas4ever",address:"Lot 33 The Belle"}];
var emailInput = document.getElementById('email'),
passwdInput = document.getElementById('passwd'),
loginBtn = document.getElementById('login-btn');
// When the user clicks on the button, execute loadData
loginBtn.addEventListener('click', loadData);
function isEmailValid(email) {
var pattern = /^[a-zA-Z0-9\-_]+(\.[a-zA-Z0-9\-_]+)*#[a-z0-9]+(\-[a-z0-9]+)*(\.[a-z0-9]+(\-[a-z0-9]+)*)*\.[a-z]{2,4}$/;
return pattern.test(email);
}
function isPasswordValid(passwd) {
return (
/[a-z]/.test(passwd) &&
/[A-Z]/.test(passwd) &&
/[0-9]/.test(passwd) &&
/^[a-zA-Z\d]+$/.test(passwd) &&
passwd.length >= 8
);
}
function areValidCredentials(email, passwd) {
return isEmailValid(email) && isPasswordValid(passwd);
}
function findUserInList(list, email, passwd) {
return list.find(function (user) {
return user.email === email && user.password === passwd;
});
}
function loadData() {
var email = emailInput.value,
passwd = passwdInput.value,
valid = areValidCredentials(email, passwd),
// We'll fill those in below
coordinator,
student;
if (!valid) {
// We return, because there is nothing else to do
return alert("Invalid user/password format. Please check and try again.");
}
// Look for a coordinator with the same email/password
coordinator = findUserInList(coordinators, email, passwd);
if (coordinator) {
alert("Welcome " + coordinator.firstName + "! You are a coordinator.");
// Do something?
} else {
student = findUserInList(students, email, passwd);
if (student) {
alert("Welcome " + student.firstName + "! You are a student.");
// Do something?
} else {
// We return, because there is nothing else to do
return alert("This user/password combination was not found.");
}
}
// I omitted the localStorage part because it did not make sense to me
// as why you would do this, but it's syntactically correct, so feel free to add it
// if it's a requirement
}
label, input, button { display: block; max-width: 300px; margin-bottom: .5em; }
<p>(Hint: the only valid user is <b>mayas.k#gmail.com</b> / <b>Mayas4ever</b>)</p>
<label for="email">Email:</label>
<input id="email">
<label for="passwd">Password:</label>
<input id="passwd" type="password">
<button id="login-btn">Login</button>
I'm quite new to JS and am trying to check if a user or any value exists in a JavaScript object in real time, the goal is to implement this in Firebase in order to prevent user registration if that username has already been taken but I am doing it locally first because Im learning. This is what I have so far.
let input = document.getElementById('input')
let btn = document.getElementById('btn')
btn.disabled = false
let users = [
{
uname: "mark"
},
{
uname: "sarah"
},
{
...others uname
}
]
input.addEventListener('input', () => {
input.value = input.value.replace(regex, "")
check(input.value)
})
function check(val) {
users.forEach((item) => {
let uname = item.uname
if (uname.indexOf(val) > -1 && uname === val) {
console.log('That user name has been taken')
btn.disabled = true
} else {
console.log('Ok')
btn.disabled = false
}
})
}
The problem with that is when I typed in the input element Im getting both the if and else triggered and while (val) matches some key/value pairs the others won't and then I am able to use whatever username Im typing which is not what I want.
How can I solved this? Thanks.
You aren't checking to see if the username has been found.
function isUsernameAvailable (val) {
for (var i = 0; i < users.length; i++) {
var uname = users[i].name;
if (uname === val) {
console.log('That user name has been taken')
btn.disabled = true
return false; // the username is taken, we can stop checking
}
}
console.log('Ok')
btn.disabled = false
return true;
}
Also, forEach doesn't let you exit the loop early and you don't need to check every user after you found a match (if you find a match).
I'm trying to hardcode a kind of log in system, for that i was trying to have two inputs and on click check if those values matched the ones in the array, the array having two objects for two possible answers…
Well, i cant get it to work, all of the suden my variables are not recognized and the overall code has gone kaput… here is the Pen
thanks in advance!
the code so far btw
$(".submit").click(function() {
//bidimensional array
var data = [{
user: "cinco",
pw: "king"
}, {
user: "manco",
pw: "wawa"
}];
var name = $(".name").val();
var pass = $(".pw").val();
if (data.user.includes(name) && data.pw.includes(pass)) {
$(".check-input").addClass('valid');
} else {
$(".check-input").addClass('invalid');
}
});
$(".input").focus(function() {
$(".check-input").removeClass("valid");
$(".check-input").removeClass("invalid");
});
You can use find() like this
if (data.find(v => v.user === name && v.pw === pass)) { ... }
Please note that using javascript as your login is highly insecure as everybody can just open the console and read the credentials.
For your comment, the => is part of an arrow function, it boils down to
if (data.find(function(v) {
return v.user === name && v.pw === pass;
})) { ... }
var data = [{
user: "cinco",
pw: "king"
}, {
user: "manco",
pw: "wawa"
}];
checkLogin(usr, pwd){
for(var index in data) {
var obj = data[index];
if(obj.user == usr && obj.pw == pwd) {
return true;
}
}
return false;
}
checkLogin('chino', 'wrongPwd'); // returns false
checkLogin('chino', 'king'); // returns true
You need to access the individual objects in the array and get the user and pw properties of those objects. The array itself doesn't have those properties.
Here's a working version that also streamlines your code:
$(".submit").click(function() {
// This is not a bidimensional array. It's just an array of objects
var data = [{
user: "cinco",
pw: "king"
}, {
user: "manco",
pw: "wawa"
}];
var name = $(".name").val();
var pass = $(".pw").val();
// You need to access the individual objects in the array and get
// the user and pw properties of those objects. The array itself
// doesn't have those properties.
// Loop through the array and check each object
// You can't return from a forEach loop, so we'll set up a variable
// that will be used after the loop is complete
var valid = false;
data.forEach(function(obj){
// Don't check for inclusion of the data, check for exact match
if (obj.user === name && obj.pw === pass) {
valid = true;
}
});
// Now that the loop is done, set the validity
$(".check-input").addClass(valid ? 'valid' : 'invalid');
});
$(".input").focus(function() {
$(".check-input").removeClass("valid");
$(".check-input").removeClass("invalid");
});
.check-input{
width:250px;
height:40px;
background-color:gray;
}
.valid{
background-color:green;
}
.invalid{
background-color:crimson;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="input name">
<input type="text" class="input pw">
<button class="submit">Submit</button>
<div class="check-input"></div>
I am having issues searching in an array of objects. Basically what my page needs to do is to create a new "client" using information entered by me, such as Full name, User name, Email and Password. Each one of these clients are objects in an array as you can see below.
var clientlist = [{"username":"John","fullname":"John Doe",
"email":"john.doe#hotmail.com","type":"client","password":"jdoe2"},
This client is already created in my js file, what I need to do is to create a new object to add to this array with this same structure. For example,
var clientlist = [{"username":"Peter","fullname":"Peter Jones",
"email":"peter.jones#hotmail.com","type":"client","password":"pjones1"},
I have written the code but it doesn't work properly, when I run the Firebug I can see that all elements have been added correctly except for the Username which value is "". I cannot seem to search for the username to see if the username that I am adding already exists, it may be a syntax mistake. I will leave my complete code below and thanks in advance for the assistance!.
var clientlist = [{"username":"John","fullname":"John Doe",
"email":"john.doe#hotmail.com","type":"client","password":"jdoe2"},
var Client = {};
function NewClient(){
var found;
var user = $("#username").val();
for (var i = 0; i < clientlist.length; i++) {
if (clientlist[i].username == user) {
found = true;
}else{
found = false;
}
}
if (found == true){
$("#msj").html("User already exists!");
}
else if(found == false){
Client["fullname"] = $("#fullname").val();
Client["username"] = user;
Client["email"] = $("#email").val();
Client["type"] = "client";
Client["password"] = $("#password").val();
clientlist[clientlist.length] = Client;
$("#msj").html("New client has been created");
}
}
Few mistakes that you made:
Forgot to close the clientlist array
Forgot to actually push the newly added client
This code below should work correcting a few mistakes that you made along the way.
var clientlist = [{
"username": "John",
"fullname": "John Doe",
"email": "john.doe#hotmail.com",
"type": "client",
"password": "jdoe2"
}];
function NewClient() {
var found = false;
var user = $("#username").val();
for (var i = 0; i < clientlist.length; i++) {
if (clientlist[i].username == user) {
found = true;
} else {
found = false;
}
}
if (found) {
$("#msj").html("User already exists!");
} else {
var newUser = {
fullname: $("#fullname").val(),
username: user,
email: $("#email").val(),
type: "client",
password: $("#password").val()
}
clientlist.push(newUser);
$("#msj").html("New client has been created");
}
}
Made a fiddle for you:
http://codepen.io/gabrielgodoy/pen/xOxoWw?editors=1011
I guess, you have several issues.
Ending bracket of the clientList
For loop and the found variable
pushing new user to the client list.
I have corrected them and included it below.
<script>
var clientlist = [{"username":"John","fullname":"John Doe",
"email":"john.doe#hotmail.com","type":"client","password":"jdoe2"}]
function NewClient(){
var found=false;
var user = $("#username").val();
for (var i = 0; i < clientlist.length; i++) {
if (clientlist[i].username==user) {
found = true;
break;
}
}
if (found){
$("#msj").html("User already exists!");
}
else{
var newUser={
fullname:$("#fullname").val(),
username:user,
email:$("#email").val(),
type:"client",
password:$("#password").val()
}
clientlist.push(newUser);
$("#msj").html("New client has been created");
}
}
</script>