javascriptisnan

user must input a number NOT a letter or special character


I cannot seem to figure this out, very new to JavaScript. I've tried isNaN and typeof maybe I'm just writing the if statements wrong.

This is the code I have

// prompt user to select password length, and what characters to include
function promptUser() {
  var passwordLength = parseInt(prompt('How many characters would you like your password length to contain?'));
  
// is length is not a number return null,
  if (passwordLength = isNaN) {
    alert('Password length must be a number.');
    return null;
  }
// password length must be greater than 8
  if (passwordLength < 8) {
    alert('Password length needs to be at least 8 characters in length');
    return null;
  }
 // length must be less than 128
  if (passwordLength > 128) {
    alert('Password length cannot exceed 128 characters in length.');
    return null;
}

I was expecting the

if (passwordlength == //(or === tried both)// isNaN) 

to check if it is a number or not but it only spits out alert('Password length must be a number.'); and ignores the return null; no matter what is entered.


Solution

  • You may be using isNaN wrong. Try isNaN(passwordLength) instead. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN