JavaScript > Global Reference

Check for numeric value in JavaScript

How to check whether a value is an illegal number (Not a numeric value) in JavaScript?


By using isNan() function we can check whether a value is an illegal number.

NOTE: The illegal number means which is not finite, legal number. This function returns output "true", if the checked value is illegal number, otherwise it returns "false".

<p>Click the below button to determine wheteher a number is an illegal number.</p>
<input type="button" onclick="mySearch()" value="Check">
<p id="myId"></p>

<script>
    function mySearch() {
        var p = isNaN(258) + "</br>";    //* This is Finite, legal number *//
        var q = isNaN(25.8) + "</br>";   
        var r = isNaN(2 * 5 * 8) + "</br>"; 
        var s = isNaN("258") + "</br>"; 
        var t = isNaN("Sheo Narayan") + "</br>"; //* This is illegal number *//
        var u = isNaN(0) + "</br>"; 
        var v = isNaN("09-Nov-2015"); //* This is illegal number *//

        var a = p + q + r + s + t + u + v;
        document.getElementById("myId").innerHTML = a;
    }
</script>

In the above code snippet we have given ID as "myId" to the second <p> element in the HTML code. There is a function mySearch() in the script code which is connected to the onclick of the HTML button.

We need to check whether a value is an illegal number. For that we are using isNan() function, this function checks the each and every varaibale which contains isNan() function and returns the output as per the function value, if the input value of isNaN() function is an illegal number it returns the output as 'true' otherwise it returns 'false'.

Onclick of the button "Check" in the HTML code fires the function mySearch() in the script code at the same time isNaN() function check whether a number is an illegal number and returns the output. 

OUTPUT

 Views: 4794 | Post Order: 182



Write for us






Hosting Recommendations