i havea signup form which have a field for email. i made a regular expression to verify it and that regex is working perfectly. that problem i am facing is that the function which does this job is not working. this will become more clear from the following:
var email = getEle('email', clas)[0].value; // 'getEle()' is a function which returns an element whose calss is the first arguement
console.log(email); // logs correct thing which means that email has been caught by the javascript
function em(){ // this function will check email
var eln = email.match(/([A-Za-z0-9\._\-]+)#([A-Za-z]+).([A-Za-z]+)/);
console.log(eln);
if(eln.length ===4){
email = email;
}else{
Error = Error + "2) Your Email address is not valid. Please enter valid email Address\n"
}
};em();// end
my email validation regex is working properly as you can see here regex101.com
error which is given to me is: Uncaught TypeError: Cannot read property 'length' of null
the first log logs correct thing but the second log logs null
if this is done in console(i am using google chrome) then no error is given.
question is, if no error is given when this thing is done manually, then why error is given to me when the same is done while writing it as a function code.
what is the mistake.
complete code:
var getEle = function(ele, type){
if(type ==="id"){
return document.getElementById(ele);
};
if(type==="class"){
return document.getElementsByClassName(ele);
};
if(type === 'tag'){
return docuemnt.getElementsByTagName(ele);
};
};
function signUpform(){
var fname = getEle('fname', clas)[0].value,
lname = getEle('lname', clas)[0].value,
email = getEle('email', clas)[0].value,
phoneNo = getEle('phoneNo', clas)[0].value,
age = getEle('age', clas)[0].value,
date = getEle('date', clas)[0].value,
username = getEle('username', clas)[0].value,
password = getEle('password', clas)[0].value,
re_pass = getEle('re_pass', clas)[0].value,
Error = "Errors List: \n";
console.log(email);
function flname(){ // this function will check the first name and the last name
if(fname === "" || lname ===""){
Error = Error +'1) You cannot leave first name and last name blank\n';
}else{
fname.value = fname.value.replace(/[0-9]+/g,"");
lname = lname.replace(/[0-9]+/g,"");
};
};flname();// end
function em(){ // this function will check email
var eln = email.match(/([A-Za-z0-9\._\-]+)#([A-Za-z]+).([A-Za-z]+)/);
console.log(eln);
if(eln.length ===4){
email = email;
}else{
Error = Error + "2) Your Email address is not valid. Please enter valid email Address\n"
}
};em();// end
};
No need to check length of matched array, just simplify your em function like this:
function em(){ // this function will check email
var eln = /\b[\w.-]+#[A-Za-z]+\.[A-Za-z]+\b/.test( email );
if (!eln)
Error = Error + "2) Your Email address is not valid. Please enter valid email";
};
Related
I have been working on a project where we can store login info so that once a user registers, the data gets saved in the localStorage object. I have mentioned some javascript code to show that:
var user = document.getElementById("user");
var pass = document.getElementById("pass");
var email = document.getElementById("email");
var user2 = document.getElementById("user2");
var pass2 = document.getElementById("pass2");
function register() {
localStorage.setItem("username", user.value);
localStorage.setItem("password", pass.value);
localStorage.setItem("email", email.value);
document.getElementById("id01").innerHTML = "Registration successful";
}
function login() {
var checkuser = localStorage.getItem("username");
var checkpass = localStorage.getItem("password");
if (checkuser === user2.value && checkpass === pass2.value) {
document.getElementById("demo").innerHTML = "You are now logged in.";
} else {
document.getElementById("demo").innerHTML = "Incorrect username and password";
}
}
In the javascript code mentioned above, i have used the localStorage object to store the values. I have stored the username in a user property, the password in a pass property and the email in an email property.
My question is: Is there any way where we can store the username, password and the email in one property(user property)?
Yes, you can do this by putting all the features you want in one object.
Example here
var user = document.getElementById("user");
var pass = document.getElementById("pass");
var email = document.getElementById("email");
var user2 = document.getElementById("user2");
var pass2 = document.getElementById("pass2");
var user = {
email:email,
pass:pass,
//.. other properties
}
then you can set like this
localStorage.setItam("USEROBJ",JSON.stringify(user));
When you want to call this you should use like
var user = JSON.parse(localStorage.getItam("USEROBJ"));
By the way you can read this
Storing Objects in HTML5 localStorage more detail about you question
You can store JSON as a string in localStorage property and then parse it
function setUser() {
localStorage.setItem('user', JSON.stringify(user));
}
function getUser() {
user = JSON.parse(localStorage.getItem('user'))
}
So I got this code that creates a html page.The function signup allows the user to register and create a password. The function checkpassword is to check if the correct password is entered for the username.It seems I have a problem in getting the item from local storage in my checkPassword function?Help will be much appreciated as I've been stuck for hours?
const PREFIX = "monash.eng1003.passwordApp.";
function checkPassword() {
var user = document.getElementById("registerUsername").value;
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var passwordToCheck = localStorage.getItem(PREFIX + user);
var passwordTwo = JSON.parse(passwordToCheck);
if (password != passwordTwo) {
alert("Don't hack" + user);
} else {
alert("Welcome" + user);
}
}
function signup() {
var user = document.getElementById("registerUsername").value;
var pass1 = document.getElementById("registerPassword").value;
var pass2 = document.getElementById("confirmPassword").value;
if ((pass1 === pass2) && (pass1 !== "")) {
if (localStorage) {
var passwordToStore = pass1;
localStorage.setItem(PREFIX + user, passwordToStore);
alert("Account created for username: " + user);
}
} else {
alert("Passwords must match and cannot be empty.")
}
}
EDIT:Thanks for pointing out that I do not need to parse it since I didn't stringify.That solved the problem but since I cannot delete the post I have to leave it here
You didn't convert the password to JSON when you stored it, so you don't need to use JSON.parse() when you retrieve it. You stored an ordinary string, you can just retrieve it and use it.
passwordTwo = localStorage.getItem(PREFIX + user);
I am trying to create a register user page and saving it into Firebase.
My form includes first name, last name, email, password and confirm password.
I am able to create a new object into my Firebase Database, but when I added the if else statement to make sure the password and confirm password matches, it keeps on giving me:
"Uncaught Error: Firebase.push failed: first argument contains undefined in property 'projectdatabase.password' error."
after the alert box.
It works fine if password and confirm password matches. How can I solve this error?
if(firebase.apps.length===0){
firebase.initializeApp(config);
var sFName = document.getElementById("sfname").value;
var sLName = document.getElementById("slname").value;
var sEmail = document.getElementById("semail").value;
if((document.getElementById("spassword").value)==(document.getElementById("sconfirmpassword").value)){
var sPassword = document.getElementById("spassword").value;
var dbRef = firebase.database().ref().child('projectdatabase');
//store the data in Javascript object
var postData = {
firstname : sFName,
lastname : sLName,
email : sEmail,
password : sPassword
};
dbRef.push(postData);
document.getElementById("response").innerHTML =
"Registered!"
} else{
alert("Re-Enter confirm password!")
var sFName = document.getElementById("sfname").value;
var sLName = document.getElementById("slname").value;
var sEmail = document.getElementById("semail").value;
if((document.getElementById("spassword").value)==(document.getElementById("sconfirmpassword").value)){
var sPassword = document.getElementById("spassword").value;
var dbRef = firebase.database().ref().child('projectdatabase');
var postData = {
firstname : sFName,
lastname : sLName,
email : sEmail,
password : sPassword
};
dbRef.push(postData);
document.getElementById("response").innerHTML =
"Registered!"
}
}
}
I have a log in form and am trying to display an error message if the log is incorrect.
For example;
If (email and password match) then set validUser to true.
If validUser equals true then redirect to home page
Else redirect them back to log in and display one of 3 messages...
Messages are:
'Log in unsuccessful' if both email and password are incorrect
'Password incorrect' if just the password is wrong
'Email incorrect' if just the email is wrong
Is it possible to have a loop to do all this? I can't figure it out....
Trying something like this too:
if (validUser==false)
{
$("message").show();
}
else if ( ..........)
{
$("passwordmessage").show();
}
I also want to display a message on the page and so far using this:
document.getElementById('message').style.display = ""
Here is my code: http://jsfiddle.net/2pkn1qrv/
So, how could I use if statements to do this and how can I correctly display a html page element using javascript or jquery?
Please ask if you need any more code or require clarification.
P.s. these are my users details
var USERS = {
users: []
};
function User(type, email, password) {
this.type = type;
this.email = email;
this.password = password;
}
var A = new User("rep", "a#a.com", "a");
USERS.users.push(A);
var B = new User("rep", "b#b.com", "b");
USERS.users.push(B);
var C = new User("customer", "c#c.com", "c");
USERS.users.push(C);
var D = new User("grower", "d#d.com", "d");
USERS.users.push(D);
module.exports = USERS;
You wont be having 3 conditions in that case. you will check email availability and password match. If anyone fails, you can display the message. I couldnt test your code but this will be the logic and i assume Users.user[x].email is the list of emails from your database. If yes, sorry to say that its a bad practise.
validUser = false;
emailAvailable = false;
passwordIncorrect = false;
for (var x in USERS.users) {
if(!emailAvailable && emailLog === USERS.users[x].email){
emailAvailable = true;
} //Checks whether email is available.
if(emailAvailable && passwordLog === USERS.users[x].password){
passwordIncorrect = true;
break;
} //Checks whether the password is correct for that email.
} // end of for
if(!emailAvailable){
console.log("Email is incorrect");
}
else if(emailAvailable && !passwordIncorrect){
console.log("Password is incorrect");}
else{
validUser = true;
console.log("Valid User");
}
if(validUser){
//redirect
}
I think my way is it worth to give a try:
First: create a Javascriptobject:
function ruleToCheck(errorRule, errorMsgContainer)
{
this.errorCondition = errorRule;
this.errorMessage = errorMsgContainer;
}
after that create an array and fill it with your rules:
var rulesList = new Array();
rulesList.push(new ruleToCheck("validUser === true", "message"));
...
Then loop through the array:
var rulesListLength = rulesList.length;
var index = 0;
while (index < rulesListLength)
{
index++;
...
}
The secret of success is the powerful eval() function within the while() loop:
if (eval(rulesList[index].errorCondition))
{
$("#"+rulesList[index].errorMessage).show();
break;
//If 'break does not work, use 'index = rulesListLength'
}
Hope it was helpful or at least leaded you into the right direction.
By the way, take care of the comments on your question.
I have a form, on the first 3 input fields (fname, lname, addr) there is an onkeyup function which checks the inputs value against a database. If there is a single match, the function offers a popup (javascript confirm) which asks if the record in the database is correct, if so will prepopulate the fields.
Problem is, most people can type faster than the function can check. If the function finds a match with "smi" but the users types "smith" before the pop up, then the confirm will appear 3 times consecutively.
What can be done about this?
Here's what I've tried, no luck
function startAjax(){
if(document.getElementById("flag").value == "yes"){
if (window.XMLHttpRequest){ xmlhttpp=new XMLHttpRequest(); }else{ xmlhttpp=new ActiveXObject("Microsoft.XMLHTTP"); }
xmlhttpp.onreadystatechange=function(){
if(xmlhttpp.readyState==4 && xmlhttpp.status==200){
var status = xmlhttpp.responseXML.getElementsByTagName('status')[0].firstChild.nodeValue;
var fname = xmlhttpp.responseXML.getElementsByTagName('fname')[0].firstChild.nodeValue;
var addr = xmlhttpp.responseXML.getElementsByTagName('addr')[0].firstChild.nodeValue;
var lname = xmlhttpp.responseXML.getElementsByTagName('lname')[0].firstChild.nodeValue;
var city = xmlhttpp.responseXML.getElementsByTagName('city')[0].firstChild.nodeValue;
var state = xmlhttpp.responseXML.getElementsByTagName('street')[0].firstChild.nodeValue;
var zip = xmlhttpp.responseXML.getElementsByTagName('zip')[0].firstChild.nodeValue;
var email = xmlhttpp.responseXML.getElementsByTagName('email')[0].firstChild.nodeValue;
document.getElementById("ajax_status").innerHTML=status;
if(status == "Found user"){
document.getElementById('pop_display').style.display = "block";
var confirmMsg = "*User Found*\n\nName: "+fname+" "+lname+"\nAddress: "+addr+"\nCity: "+city+"\nState: "+state+"\nZip: "+zip+"\nEmail: "+email+"\n\nClick 'OK' To populate fields or click 'Cancel' if this is not the correct info.";
var fillOrNot = confirm(confirmMsg);
if(fillOrNot === true){
document.getElementById('fname').value = fname;
document.getElementById('lname').value = lname;
document.getElementById('address').value = addr;
document.getElementById('city').value = city;
document.getElementById('state').value = state;
document.getElementById('zip').value = zip;
document.getElementById('email').value = email.trim();
document.getElementById('flag').value="no";
}else{
document.getElementById('flag').value="yes2";
document.getElementById("ajax_status").innerHTML="Aborted";
}
document.getElementById('pop_display').style.display = "none";
}
}
}
var param1 = document.getElementById('fname').value;
var param2 = document.getElementById('lname').value;
var param3 = document.getElementById('address').value;
var url = "https://www.mywebsite.com/ajaxhandler.php?fname="+param1+"&lname="+param2+"&addr="+param3;
xmlhttpp.open("GET",url,true);
xmlhttpp.send(null);
}
}
Use 'blur' of javascript or 'onfocusout' of jQuery instead of 'onkeyup'
Add a variable outside startAjax, like 'checking', that you will set to 'true' when you are waiting for the response from database - once you receive the responce, set it to 'false.' Then, in the point of your code where you're calling the database, check whether or not you're already waiting for a responce (if you are, just skip the call altogether)
It also helps to delay the first call by a bit, like 100 milliseconds, so the user can enter a couple of characters before it - javascript's timeout will do the job.