Reputation: 185
I'm getting a numeric value from a form. Then I check to see if it's NaN. If it is a number I want to set that value to a variable. The problem is that when I enter a valid number I still get an alert and the number isn't passed to the variable "date". How should I modify my statement so that when it is a valid number I can assign it to the variable date?
var adate = document.getElementById("dueDate").value;
if ( adate == NaN || " ") {
alert("Please enter a due date");
return;
}
else {
var date = (new Date()).setDate(adate);
}
processDate(date);
Upvotes: 9
Views: 41192
Reputation: 11
By using isNaN method we can verify if the given input is number or not.
let num1 = parseInt(prompt('Enter your number-1'));
let num2 = parseInt(prompt('Enter your number-2'));
alert(num1 + " is of type " + typeof num1 + " & " + num2 + " is of type " + typeof num2);
if (isNaN(num1) || isNaN(num2)) {
alert("Can not add incompatible types");
} else {
let sum = num1 + num2;
alert("Sum is " + sum);
}
Upvotes: 1
Reputation: 5711
As strange as it seems, NaN !== NaN
.
if (adate !== adate || adate !== " ") {
//...
}
The isNaN
function would work in a lot of cases. There is a good case to be made that it is broken, though.
One nice way of getting around this is:
MyNamespace.isNaN = function (x) {
return x !== x;
}
Upvotes: 10
Reputation: 67189
Use Javascript's isNaN() function.
Checking equality with NaN is always false, as per IEEE's standards. Stephen Canon, a member of the IEEE-754 committee that decided this, has an excellent answer explaining this here.
Upvotes: 19
Reputation: 237847
You have two problems here. The result is that the conditional will always pass. This is what it does:
adate == NaN // first, test if adate == NaN (this always returns false)
|| // if the first test fails (i.e. always), carry on checking
" " // test if the string " " is truthy (this always returns true)
The ||
does two separate checks. It does not test to see if adate
is "either NaN
or " "
", which seems to be what you expect.
Your code might as well say
if ( true ) {
You would be able to sort this out, however, if you tried two comparisons:
if ( (adate == NaN) || (adate === " ")) {
As other people have said, however, this doesn't work, because NaN !== NaN
. So the solution is to use isNaN
:
if (isNaN(adate) || (adate === " ")) {
Upvotes: 4