Search code examples
javascripttype-coercion

isFinite of space giving true value


I am trying to validate a price field. I was trying this:

var productId = document.getElementById("productId");
var productName = document.getElementById("productName");
var productPrice = document.getElementById("price");

alert(isFinite(productPrice.value));

if(isNaN(productPrice.value)||!isFinite(productPrice.value)){
    error = document.getElementById("priceError");
    error.innerHTML = "Please enter correct value";
    productPrice.style.border="thin solid red";
}else{
    error = document.getElementById("priceError");
    error.innerHTML = "";
}

The line alert is giving me true when the input is space/ multiple spaces only. This is my HTML page.

<td>Price</td>
<td><input type = "text" id = "price" size = "14"/></td>

Thanks


Solution

  • Why this happens i cant say, but this code should solve the problem

    isFinite(parseFloat(" ")) // false
    // because -->
    parseFloat(" "); // => result NaN
    // tested in Chrome 27+ on Win7
    

    in the MDN refernce of isNaN here it says

    isNaN(" ");     // false: a string with spaces is converted to 0 which is not NaN
    

    Update:

    in the Reference of isFinite found Here it states that isFinite only returns false if the argument is:

    • NaN
    • positive infinity, (Number.POSITIVE_INFINITY)
    • negative infinity (Number.NEGATIVE_INFINITY) In any other Case it returns true. (like Paul S mentioned)

    Now i Think i got all loose ends, and in that course learned something. :)