How to validate the given input is a number or not using Javascript?
Contents
isNan() function in Javascript
The function isNan() is used to determines whether a value is not a number. It will returns the true if the value is not a number. Otherwise it returns false which means the given input is a number.
Syntax
1 |
isNan(value) |
The value should be given as parameter in the isNan() function. Then it is tested by isNan() function and returns the true/false value based on the input.
Example for number validation in Javascript
Javascript code with isNan() function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
<html> <head> </head> <body> <form name="testForm"> Mobile Number: <input type="text" id="mnumber" name="mobile"> <input type="submit" value="Submit" onclick="return validatenumber()"> <div id="mylocation"></div> <div id="mylocation1"></div> </form> <script type="text/javascript"> function validatenumber() { var mobile_number = document.getElementById("mnumber").value; if (isNaN(mobile_number)) { document.getElementById("mylocation").innerHTML="Enter only number"; document.getElementById("mylocation").style.color="Red"; return false; } else{ document.write(mobile_number + " is a number <br/>"); return true; } } </script> </body> </html> |