I have stored username and password to a key login in local storage and I need to validate from home page using JavaScript code. function validlogin(event)
function validlogin(event) {
var user = document.getElementById('user').value;
var psw = document.getElementById('psw').value;
var entriesJSON = localStorage.getItem('login');
if (!entriesJSON) {
alert("Nothing stored!");
event.preventDefault();
return;
}
var allEntries = JSON.parse(entriesJSON);
for (var i = 0; i < login.length; i ) {
var entry = login[i];
var username = entry.user;
var password = entry.pass;
var email = entry.email;
if (user == storedUserName && psw == storedPassWord) {
alert("Successfully logged in!");
return;
}
alert('Invalid Username or Password! Please try again.');
event.preventDefault();
window.location = "test.html";
}
}
CodePudding user response:
Just you have to add a else condition like below
if (user == storedUserName && psw == storedPassWord) {
alert("Successfully logged in!");
return;
}
else{
alert('Invalid Username or Password! Please try again.');
event.preventDefault();
window.location = "test.html";
}
If you're not using else condition, It definitely pass the if condition and says
alert("Successfully logged in!");
but after that it gives an
alert('Invalid Username or Password! Please try again.');
So just use else condition. And then all good. Good work champ ; )
CodePudding user response:
function validlogin() {
var user = document.getElementById('user').value;
var psw = document.getElementById('psw').value;
var items = JSON.parse(localStorage.getItem('login'));
for (let i = 0; i < items.length; i ) {
if (items[i].username == user && items[i].password == psw)
{
alert("welcome");
}
}
}