This is for a Java script course that Im taking…
I need to create a simple user-login script. When the page loads a prompt pops up asking for the user name. If the correct username is entered, another prompt is displayed asking for a password.
If both the username and valid, then you a sucessful message, otherwise you get a failure message.
I’ve written all of the code, but am having trouble with validating the username and password.
You can see in my code that I’m using two array lists. One for users and another for passwords. When I run my code, if I type in the correct username and password for user1, it validates, BUT if I enter user1 and the password for user2, it still validates.
<script type="text/javascript">
//Input from user
var userId = prompt("Enter UserID", "");
userId_lowercase = userId.toLowerCase();
//Username and Password Arrays
var userIdList = new Array();
userIdList[0] = "user1";
userIdList[1] = "user2";
userIdList[2] = "user3";
var passwordList = new Array();
passwordList[0] = "pass1";
passwordList[1] = "pass2";
passwordList[2] = "pass3";
//Process input and check for authentication
//Check for correct userId
var userIdFound;
for (index in userIdList)
{
if (userId_lowercase == userIdList[index])
{
userIdFound = "Y";
break;
}
}
if (userIdFound == "Y")
{
document.write("<p>" + userId + " was Found</p>"); ;
//Check for correct Password
var password = prompt("Enter Password", "");
var passwordFound;
for (index in passwordList)
{
if (password == passwordList[index]) // This is where I need help,
// how do I say
// "if password is from the passwordList && it matches the userId index selected"
{
passwordFound = "Y";
break;
}
}
if (passwordFound == "Y")
{
document.write("<p>Welcome to the class!</p>");
}
else
{
document.write("<p>Error: Password is not valid.</p>");
}//END Password Check
}
else
{
document.write("<p>" + userId + " was NOT found</p>");
}//END USERID Check
</script>
First of all, I wouldn’t use for-in, I’d use a simple for loop to iterate over the array. Then you could store the index that matches the user name to compare it to the password array:
Then, in your password loop you’d say:
That’s the simple way around the problem. I don’t know how much you’ve learned but you could also use an array of objects:
And then loop through that array once after asking for the name and password and seeing if they match:
The thing to keep in mind is that you have to link the user name to the password somehow. The way you’re currently doing this is by the index in both arrays, but that isn’t guaranteed. It’d be much better to link the two bits of information in some way, as in the array of objects above.