I want to loop the local storage for the password and username to check if correct and alert a message if or if not.
The code is working well, but I don't know where to write the "invalid username" message because the loop goes through every record, so the messages pops ups for every record check until it finds it.
What I want is to pop up the message when the search is done.
Here is my code:
$("#login").click(function(){
var username =$("#user").val();
var password =$("#pass").val();
var userCount = localStorage.getItem('userCount');
for (i=1;i<=userCount;i++) {
var user = JSON.parse(localStorage.getItem("user" + i));
if((user.username == username)||(user.password == password)){
alert("welcome "+username);
} else {
alert("Invalid Username");//this message keeps poping up on every record until username found
}
}
});
Put the loop inside a function.
Return true (or the user object) from that function if anything inside the loop matched.
Return false after the loop (which you'll only reach if nothing matches).
Handle your alert outside the function based on the return value of calling it.
Set a boolean variable to true when you find a match, and stop the loop using break. Otherwise, if the boolean is still false after the loop completes, no match was found.
$("#login").click(function(){
var username =$("#user").val();
var password =$("#pass").val();
var userCount = localStorage.getItem('userCount');
var foundOne = false;
for (i=1;i<=userCount;i++) {
var user = JSON.parse(localStorage.getItem("user" + i));
if((user.username == username)&&(user.password == password)){
foundOne = true;
break;
}
}
if(foundOne) {
alert("welcome "+username);
// other "welcome" code
} else {
alert("Invalid Username");
}
});
NB, you may want to use the && operator instead of || here:
(user.username == username)&&(user.password == password)
otherwise you may get a match for one user who has the same password as another.
Related
Problem:
Its a sign up a new user form with HTML.
Im supposed to store multiple arrays(containing "username: username, password: password, topScore: 0) in one JSON key ("user" key) all it does right now is that it stores only one array, if I enter another one it just overwrites the current.
// In HTML the function is called:
//<form name = "signup" onsubmit="registerNewUser()>
var user = [];
function registerNewUser() {
/** Get the value of username, password and repeat password **/
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var passwordRepeat = document.getElementById("passwordRepeat").value;
/** boolean variable to check if the username already exits **/
var usernameExists = false;
/** if statement to check if password and passwordRepeat match **/
if (password == passwordRepeat) {
/** For loop to scan through registered users to check if username is already in use **/
for(let i = 0; i < user.length; i++) {
if(user[i].name == username) {
usernameExists = true;
}
}
if (usernameExists) {
alert("This user name already exists.");
}
else {
/** Put array into users in JSON storage with username,password and score values **/
user.push( {name: username, password: password, topScore: 0} );
localStorage.setItem("user", JSON.stringify(user));
alert("New account successfully created!");
/** Set variable usernameExists to its original value **/
usernameExists = false;
}
}
else {
alert("Passwords do not match. Please try again.");
}
}
i used your code and added it to a fiddle. But instead of input fields, i used global variables and just set new values to those.
html:
<div id="userArray"></div>
<div id="localStorage"></div>
js:
var Username = 'Peter';
var Password = 'Parker';
var PasswordRepeat = 'Parker';
/** your function, but instead of input fields using my variables to set the respective variables inside the function **/
registerNewUser();
document.getElementById("userArray").innerHTML = JSON.stringify(user);
document.getElementById("localStorage").innerHTML = localStorage.getItem("user");
Username = 'Gwen';
Password = 'Stacy';
PasswordRepeat = 'Stacy';
registerNewUser();
document.getElementById("userArray").innerHTML = JSON.stringify(user);
document.getElementById("localStorage").innerHTML = localStorage.getItem("user");
registerNewUser();
It runs perfectly fine... beside the things that #HMR and #Shubham Jain mentioned.
you should rename your array to users, so that everybody knows it contains multiple users and not just one. And if you dont initialize users with the localStorage item, what point in storing them there anyway.
I think you are just testing something and thats why you store the passwords in the localStorage. Otherwise it would be better to store those sensitive informations in a backend application. And encrypt them.
I would have commented this, but since my reputation is below 50, i can't :-(
Got it fixed: 1. changed onsubmit="return registerNewUser(users)" 2. Put return false; inside else statement where user.push is used 3. Put return false; inside else statement after alert("Passwords do not match") Thank you guys!
i'm building a quizz app , which asks me to : Add user authentication: allow users to log in, and save their login credentials to local storage (HTML5 browser storage). what i want to add is to check if the user name && password (together, because you can have the same username and not the same password and vice versa), so i can prompt a "Welcome back (name of the user)".
i spent 3 days trying to figure out which logic works , tried everything but every time i get a logic problem where things doesn't go the way it should be , here's the code :
var usersinfo = {
users : []
}
localStorage.setItem("users", JSON.stringify(usersinfo.users))
function registerInfo(){
var name = document.forms[0].username.value;
var pw = document.forms[0].pw.value;
if (name === "" || pw === "") {
alert ('please complete all the forms')
} else {
var adding = JSON.parse(localStorage.getItem("users"));
// logic that goes here : i tried everything , looping...etc
}
return false;
}
Note that the function is attached to a button , and everything works fine on the HTML , the problem is in login logic .
Untested, but try something like this:
const users = JSON.parse(localStorage.getItem("users"));
if (users.some((user) => {
return user.name === document.forms[0].username.value;
})) {
alert('Welcome back!');
}
Basically, we use some on the array to loop through and figure out if any of the elements have the same name as the one from your form. If they do, we immediately stop looping and return true. If not, we return false.
See also: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some
And, do take #AnilRedshift's advice and don't store usernames/passwords in localstorage...
I have the simple function of doRegisterUser() which basically uses a function defined in a provider to check if username already registered or not. In the following code, I print to console, call provider's function and then print to console. Simply I am doing this just to observe the sequence of execution. What I want is to have checkUsernameReserved() execute and then any the console print to happen.
How can this be accomplished?
doRegisterUser() {
var self = this;
/*Step A - Check username provided by user is taken or not. If no username taken, create random username*/
console.log("Before checkUsernameReserved() execution");
self.firebaseProvider.checkUsernameReserved(self.username);
console.log("After checkUsernameReserved() execution");
}
and this is the provider function which uses the firebase:
checkUsernameReserved(username:string): any{
/*Check usernamesTaken table for provided username*/
firebase.database().ref('/usernames_taken/' + username).once('value').then(function(snapshot) {
/*Check if username is taken.*/
if(snapshot.val() != null && snapshot.val() != "")
{
console.log("Username Taken");
}else{
console.log("Username Available");
}
})
}
The current output I am getting in console is:
Before checkUsernameReserved() execution
After checkUsernameReserved() execution
Username Taken
Two things:
Return your promise from checkUsernameReserved
Put code that must run after the check in the .then of that promise.
So:
doRegisterUser() {
var self = this;
/*Step A - Check username provided by user is taken or not. If no username taken, create random username*/
console.log("Before checkUsernameReserved() execution");
self.firebaseProvider.checkUsernameReserved(self.username).then(() => {
// Put code that must run after the check in here...
console.log("After checkUsernameReserved() execution");
});
}
checkUsernameReserved(username:string): any{
/*Check usernamesTaken table for provided username*/
// !! note the return !!
return firebase.database().ref('/usernames_taken/' + username).once('value').then(function(snapshot) {
/*Check if username is taken.*/
if(snapshot.val() != null && snapshot.val() != "") {
console.log("Username Taken");
} else {
console.log("Username Available");
}
});
}
This is just a best practice question that I have run into and can't find the answer for. Any input is welcome! (Backed up responses with data/research would be amazing)
Example Save Button
When my save button is pressed, I want to do some validation, name (must be first and last), age (must be from 0 - 125), email (valid email address) and if these are all true, I want to "save" the user (to a db or wherever doesn't matter)
Right now my functions are set up
// Global error handler for example
var errors = {};
// Save Button Function
saveButton = function(dataModel) {
var valid = true;
valid = validateName(valid, dataModel.name);
valid = validateAge(valid, dataModel.age, 'extraParam');
valid = validateEmail(valid, dataModel.email, 'secondParam', 'thirdParam');
valid = (dataModel.red) ? validateRedUser(valid, dataModel) : valid;
if (valid) {
// Save user to database
}
else {
// alert to user an error has occured
// user errors object to respond with the errors
}
}
I feel like passing around the valid state to each sub validation function is not the best approach to a problem like this. It works, but can it be improved?
Edit: A sub-validation function would look something like:
validateName = function(valid, dataModel.name) {
if (!dataModel.name) {
valid = false;
// access global error handler to save error
errors.name = 'error in the name';
}
return valid;
}
Taking your sample function added the valid state condition check.
validateName = function(valid, dataModel.name) {
if (!dataModel.name && valid) {
valid = false;
// access global error handler to save error
errors.name = 'error in the name';
}
return valid;
}
On CRM 2013 on-premise, I'm working to write a javascript that checks for email validation. The field can contain a list of email address, however if the email is not valid, it will not let the users save the form.
I got the splitting and validating to work fine now.
However I continue to have problems to prevent users from saving the form.
On the OnChange, I check the box on the "Pass execution context as first parameter"
I user the preventDefault() function as suggested by an MSDN article however I keep getting error message "Unable to get property 'preventDefault' of undefined or null reference".
Any idea is appreciated. Here's my code:
function EmailTest(EmailField)
{
var Email = /^([a-zA-Z0-9_.-])+#([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
if(Email.test(EmailField))
{
return true;
}
else
{
return false;
}
}
function CheckEmailString(context)
{
try
{
var EmailString = context.getEventSource().getValue();
if (EmailString != null)
{
var separator = [" ", ",", ";", "|"];
var EmailArray = EmailString.split(separator);
var Flag = true;
for(var i = 0;i < EmailArray.length;i++)
{
if(!EmailTest(EmailArray[i]))
{
Flag = false;
break;
}
}
if(Flag != true)
{
alert("The list of emails entered contain invalid email format. Please re-enter");
context.getEventArgs().preventDefault();
}
}
}
catch(err)
{
alert(err.message);
}
}
you get the error
Unable to get property 'preventDefault' of undefined or null reference
because the getEventArgs is available only when you are inside the save event, it's not available inside onchange event.
You should add the validation check also inside the save event if you want to stop the save.
Could I suggest you might try updating it to the full version of the method ie
Xrm.Page.context.getEventArgs.preventDefault().
I understand when working in CRM you have to reference use the full names in order for your function to see the prevent default method.
Hopefully that helps but if not good luck in seeking a solution