Question

I wrote this code, but only the first condition is working:

if(document.getElementById('v').value == Infinity) {
    //alert
}
else if(document.getElementById('v').value == -Infinity) {
    //alert
}       
else if(document.getElementById('v').value == undefined) {
    //alert
} 
else if(document.getElementById('v').value == isNaN) {
    //alert
}

Why don't the other conditions (-Infinity,undefined,isNaN) work?

Was it helpful?

Solution

You can throw new exceptions in Javascript with the throw keyword (see the example below).

isNaN is a function

To check the validity of a number use: Number.NEGATIVE_INFINITY or Number.POSITIVE_INFINITY

In other words:

if (typeof document.getElementById('v') === 'undefined' ||
    document.getElementById('v').length === 0)
  throw new TypeError("Undefined value");
else if(parseInt(document.getElementById('v').value, 10) == Number.POSITIVE_INFINITY)
  throw new RangeError("Value is too big");
else if(isNaN(document.getElementById('v').value))
  throw new TypeError("Value must be a valid number");

You can fetch theses Exceptions like:

try {
 // call your checkup function here
} catch (exception) {
 alert ("Oh bad... Exception detected: " + exception);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top