Home > front end >  JavaScript - Form validation, want username/password validation but it submits with no issues
JavaScript - Form validation, want username/password validation but it submits with no issues

Time:11-10

I'm sure I'm missing something obvious here but I've had a really good look over this, combing for typos and such but I can't see what the problem is. I want this to be a simple form that requires a username/password combination to validate. The usernames/passwords having to match hasn't been implemented yet because my initial testing can't get over this first hurdle of the form always validating!

I've definitely made a solid go at it and I feel bad I'm getting stuck here, even looking over tons of references and comparing them to my own. I'm not even sure if the event listener itself is the problem or if the problem comes from poor coding in the function. Opening console in browser shows me no errors either. Could anybody point out where my issue is? Thanks.

"use strict";

let loginform = document.forms.login;
loginform.addEventListener("submit", checkLogin);
let users = [];
let pwords = [];
users = ["Administrator", "Manager", "Cleric", "Scribe"];
pwords = ["Password01", "Password", "Admin", "P@ssword"];

//*** NOTE: the password for each username is specific. Use the the alignment of the data in the table above (i.e. the password for the Administrator account is Password01, etc.). ***


function checkLogin() {
  var usernameInput = loginform.getElementById("Username").value;
  var pwInput = loginform.getElementById("Password").value;

  //.includes is what we need for the array checking if statements

  //For Loop 1
  for (usernameInput in users) {
    if (!users.includes(usernameInput)) {
      window.event.preventDefault();
      alert("Your username is incorrect. Please try again.")
      loginform.user.focus();
      return false;
    } else {
      //For Loop 2
      for (pwInput in pwords) {
        if (!pwords.includes(pwInput)) {
          window.event.preventDefault();
          alert("Your password is incorrect. Please try again.")
          loginform.pword.focus();
          return false;
        }
      }
    }
  }
}
<h1 id="main">Login to Umbrella Corporation</h1>
<div id="container">
  <form name="login" action="success.html" method="POST">
    <input type="text" name="user" id="Username">
    <br>
    <br>
    <input type="password" name="pword" id="Password">
    <br>
    <br>
    <input type="submit" value="Submit">
    <input type="reset" value="Reset">
  </form>
</div>

CodePudding user response:

The form element does not have a getElementById.

Change to one of these

var usernameInput = loginform.user.value;
var pwInput = loginform.pword.value;


var usernameInput = loginform.querySelector("#Username").value;
var pwInput = loginform.querySelector("#Password").value;


var usernameInput = document.getElementById("Username").value;
var pwInput = document.getElementById("Password").value;

You do NOT need to loop and then use includes

if (!users.includes(usernameInput)) 

is enough

Here is an optimised test

function checkLogin(e) { // event is available here
  const usernameInput = loginform.user.value;
  const pwInput = loginform.pword.value;
  if (!users.includes(usernameInput)) {
    e.preventDefault();
    alert("Your username is incorrect. Please try again.")
    loginform.user.focus();
    return false;
  } / no need for else after a return
  if (!pwords.includes(pwInput)) {
    e.preventDefault();
    alert("Your password is incorrect. Please try again.")
    loginform.pword.focus();
  }
}

CodePudding user response:

I think the problem here is that you're trying to loop through your data using the input provided:

var usernameInput = loginform.getElementById("Username").value;

for (usernameInput in users) {...}

This won't work. What you can do is find if the username that the user has provided is present in the array.

var usernameInput = loginform.getElementById("Username").value;

const userIndex = users.indexOf(usernameInput);

If a user is found, it will return a valid index, else it'll return a -1. You can use this to throw an error to the user.

You can do the same with the password:

var pwInput = loginform.getElementById("Password").value;

const pwIndex = pwords.indexOf(pwInput);

At the final check, you can compare the two indices. If they are equal, they are the right combo, else it's an incorrect username/password combo.

if(pwIndex === userIndex && pwIndex !== -1){...} // Success
else {...} // Failure

Finally, this is how your JavaScript should look like:

    function checkLogin() {
      var usernameInput = loginform.getElementById("Username").value;
      var pwInput = loginform.getElementById("Password").value;

      //.includes is what we need for the array checking if statements

      const userIndex = users.indexOf(usernameInput);
      const pwIndex = pwords.indexOf(pwInput);

      if(userIndex === -1 || pwIndex === -1) {
          alert("Your username/password is incorrect"); // Always better to provide a generic error. You don't want malicious users to know which part they're getting wrong.
      }
    }
  • Related