Javascript is_numeric()
Click here to view the is_numeric() demo (URL: /javascript-is-numeric-demo.html)
There is no built-in is_numeric() function in JavaScript as there is in PHP.
However, here is a simple is_numeric() function that you can copy and paste into
your JavaScript:
The Function
Warning! is_numeric() doesn't always work if you are validating form input!
This is because form inputs are strings, even if the user typed a number.
When validating form input, use this:
Using is_numeric
You can use is_numeric() right in your JavaScript code, just like you would use
it in PHP. In this example, we figure out if the variable age is a number:
Using form_input_is_numeric()
Use form_input_is_numeric() when validating form input. For example:
Or, when pulling input from a form:
Code Explanation
This is a very simple JavaScript function.
The typeof() function accepts any input and will return that input's type. So,
we just need to be sure that the type of our input is 'number'.
Common JavaScript variable types include string, Boolean, number, function,
object, and undefined.
In form_input_is_numeric() we also use the JavaScript function isNaN(). NaN
stands for "Not a Number". So, if the input is not a number, isNaN() returns
true.