Simple login validation code in JavaScript

This simple login validation code works by first taking the values entered by the user in the username and password input fields using document.getElementById().value and storing them in variables. When the Login button is clicked, the login() function runs and compares the entered values with predefined correct credentials (for example, username "admin" and password "1234") using an if condition. If both the username and password match exactly, a success message is displayed on the page by updating the text of a paragraph element; otherwise, an error message is shown. In short, the logic checks user input against fixed values and then uses conditional statements and DOM manipulation to display the appropriate result.

<!DOCTYPE html>
<html>
<body>

  <input type="text" id="username" placeholder="Username">
  <input type="password" id="password" placeholder="Password">

  <button onclick="login()">Login</button>

  <p id="result"></p>

  <script src="script.js"></script>

</body>
</html>
function login() {
  let user = document.getElementById("username").value;
  let pass = document.getElementById("password").value;

  if (user === "admin" && pass === "1234") {
    document.getElementById("result").innerText = "Login Successful";
  } else {
    document.getElementById("result").innerText = "Wrong Credentials";
  }
}



Leave a Reply

Your email address will not be published. Required fields are marked *