Reputation: 1
i am trying to validate email address but this code is not working please let me know how to fix this issue.
function submitdata() {
var email = document.getElementById('email');
var password = document.getElementById('password');
let user = localStorage.getItem('user');
var userObj = [];
for (var i = 0; i <= userObj.length; i++) {
if (email.value === userObj[i].useremail) {
alert("already registered")
}
else if (user === null) {
var userObj = [];
}
else {
userObj = JSON.parse(user);
userObj.push({ useremail: email.value, userpw: password.value })
localStorage.setItem("user", JSON.stringify(userObj));
email.value = "";
password.value = "";
}
}
}
Upvotes: 0
Views: 61
Reputation: 382
var userObj = [];
Looks like this is the issue. The length of the userObj is 0
.
if (email.value === userObj[i].useremail)
Here the userObj is empty. The 0th index never there in first place.
I tried to simulate the same case. You should have got error something like this.
let users = []
console.log(users[0].email);
VM329:1 Uncaught TypeError: Cannot read property 'email' of undefined
at <anonymous>:1:10
(anonymous) @ VM329:1
Execute this loop only when you have more than one item in your userObj
Upvotes: 2