Page reloads before reaching else statement in javascript - javascript

The problem in the code below resides in the if...else statement. If a user tries to create an account with a username or email already present in localStorage the program displays an error message. This works fine however if the if statement is false the page reloads before reaching the else statement. I have used console.log to check whether the else statement is run however as stated above the page reloads before ever reaching the else statement. I have also tried putting event.preventDefault in the if statement however that doesnt work either. Any help would be greatly appreciated. Thanks in advance.
Edit: the function is called using onclick in html when the button is pressed.
function storeRegistrationInfo(){
let person = {};
person.fullname = document.getElementById("regFullName").value;
person.username = document.getElementById("regUserName").value;
let username = document.getElementById("regUserName").value;
person.email = document.getElementById("regEmail").value;
person.password = document.getElementById("regPassword").value;
person.repeatedPassword = document.getElementById("repeatPassword").value;
let per = JSON.parse(localStorage.getItem(username));
if (person.username === per.username || person.email === per.email){
document.getElementById("signUpStatus").innerText = "Username or Email already taken!";
}else {
localStorage[person.username] = JSON.stringify(person);
}
event.preventDefault();
}

Andre, you are not receiving the event object.
Assume you are triggering this as part of onClick() ?
Try adding :
function storeRegistrationInfo(event)

Maybe need to add:
if( !(person === undefined) &&(person.username === per.username || person.email === per.email))

Related

Checking for login credentials in HTML5 Storage

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...

CRM: Javascript to Check Email Validation and Prevent Saving if not 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

looping the local storage

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.

How do I access the querystring using javascript?

I have a querystring which looks like this page3.html?redesigndata=value which it appears if its redirected from page1.html and page3.html?new=yes or no when redirected from page2.html. Here is the code I'm using to find out what the querystring is and do some functions on page3.html
var locurl = window.location.search;
if (locurl.substring(0, 13) === '?redesigndata') {
alert("redesign!");
} else if (locurl.substring(0, 4) === '?new') {
visit = locurl.substring(5);
alert("somthing!");
if (visit === 'yes') {
alert("first!");
} else if (visit === 'no') {
alert("again!");
}
}
but I don't get any alerts when I try this script and I cant find out what's wrong with it.
Try using this function
function getQueryString() {
var result = {}, queryString = location.search.substring(1),
re = /([^&=]+)=([^&]*)/g, m;
while (m = re.exec(queryString)) {
result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
return result;
}
// ...
var myParam = getQueryString()["myParam"];
Check like this
if(getQueryString()["redesigndata"] != "")
There is nothing wrong with the code you posted. If the alerts never fire, it's because the conditions are never met. Once a query string is added to the URL that DOES match one of those you listed in your code, the alert does fire.
Also, beware you're (seemingly) creating global vars.
The script works on my box. Please put this script inside script tags

How to solve client side validation problem?

I am working on a project and need to do some client side validation.
I am doing all validations by calling the onsubmit() method.
The problem that I am facing is that the validation runs just fine when I put into comments a few other statements but not otherwise.
My code:
var speak1=document.forms["form"]["speak1"].value
b = checkSpeakLanguages(speak1);
if(b==false){
return false;
}
which calls checkSpeakLanguage works properly.
But the following code works only when the above is put in comments:
var m= document.forms["form"]["maritalStatus"].value
b = checkMaritalStatus(m);
if(b==false){
return false;
}
Please help me. Please tell me why both the second part does not work when the other is present.
If the first b returns false, you return before the second part can execute. Combine the functions for your submit handler to something like:
function checkSubmit(){
var cansubmit = true,
speak1 = document.forms["form"]["speak1"].value,
m = document.forms["form"]["maritalStatus"].value;
if(!checkSpeakLanguages(speak1) || !checkMaritalStatus(m)) {
cansubmit = false;
}
return cansubmit;
}

Categories