0

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 = "";
        }
    }
}

1 Answer 1

2
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

Sign up to request clarification or add additional context in comments.

1 Comment

@Jahanzaib Kindly accept the answer if it helps you ! Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.