Reputation: 1
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.
Upvotes: -3
Views: 218
Reputation: 3219
You are Setting your passwordLength to isNan
every time:
if (passwordLength = isNaN) {
alert('Password length must be a number.');
return null;
}
Use:
if isNaN(passwordLength) {
alert('Password length must be a number.');
return null;
}
A single Equals =
is a assignment operator and not a comparative operator.
Therefore your Code will go into this IF statement every time.
Please change this to a ==
, or ===
for this code to run better.
Here is some reading on the topic for you: https://www.w3schools.com/js/js_comparisons.asp
Upvotes: 0
Reputation: 190
This part if (passwordLength = isNaN)
contains a typo. the "equal to" comparison operator is '==' or '===' (strictly equal).
Also you should compare it with null, not isNaN.
Assuming that you are using HTML for input, you will be way better off to use the <input type="number"*gt; and set the minimum and maximum values.
Upvotes: -2
Reputation: 1097
You may be using isNaN
wrong. Try isNaN(passwordLength)
instead. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN
Upvotes: -1