Skip to content Skip to sidebar Skip to footer

Javascript Login System Checks If ("userpassword") == Undefined Not Working

So basically in an html file, I have an input field, with the id 'UserPassword'. In my .js file I have a function register() where it checks if you are Registered, and if not, if t

Solution 1:

If the user left any input field empty, then mostly the value will be empty, which means that if you use the length property on your input you will get zero as the length of the input by the user.

Checking for NULL or undefined is not much required here, but still, you can check for the same if you want.

document.getElementById("register-user").addEventListener("click", register);

functionregister() {


  let userName = document.getElementById("user-name");
  let userPassword = document.getElementById("user-password");

  if (userName.value == undefined || 
      userName.value == null || 
      userName.value.length == 0) {

          console.log("Please provide user name");
  }
  elseif (userPassword.value == undefined || 
           userPassword.value == null || 
           userPassword.value.length == 0) {
 
             console.log("Please provide user password");
  }
  else {
      console.log("Everything is fine. You can register user.");  
  }
}
<inputtype="text"id="user-name"placeholder="Enter User Name" /><br /><br /><inputtype="password"id="user-password"placeholder="Enter User Password" /><br /><br /><buttonid="register-user">Register</button>

If you like to reduce some lines of code, you can use the exclamation mark (!) symbol, called a bang, which is the logical NOT operator.

You can replace

userName.value == undefined || 
 userName.value == null || 
 userName.value.length == 0

To

!userName

And for

userPassword.value == undefined || 
userPassword.value == null || 
userPassword.value.length == 0

To

!userPassword

And it will evaluate everything to empty strings (""), NULL, undefined, false.

document.getElementById("register-user").addEventListener("click", register);

functionregister() {


  let userName = document.getElementById("user-name");
  let userPassword = document.getElementById("user-password");

  if (!userName.value) {
     console.log("Please provide user name");
  }
  elseif (!userPassword.value) {
      console.log("Please provide user password");
  }
  else {
      console.log("Everything is fine. You can register user.");  
  }
}
<inputtype="text"id="user-name"placeholder="Enter User Name" /><br /><br /><inputtype="password"id="user-password"placeholder="Enter User Password" /><br /><br /><buttonid="register-user">Register</button>

Thus by using an exclamation mark (!) you get more flexibility to change for a variety of range of user input.

Post a Comment for "Javascript Login System Checks If ("userpassword") == Undefined Not Working"