JavaScript is_numeric function
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
<script type="text/javascript">
function is_numeric(input){
return typeof(input)=='number';
}
</script>
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:
<script type="text/javascript">
function form_input_is_numeric(input){
return !isNaN(input);
}
</script>
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:
<script type="text/javascript">
//is age a number?
if(is_numeric(age)){
alert("Your age is a number!");
} else {
alert("Your age is not a number...");
}
</script>
Using form_input_is_numeric()
Use form_input_is_numeric() when validating form input. For example:
<input type="text" id="testinput" />
<button onclick="alert(form_input_is_numeric(document.getElementById('testinput').value))">Is it numeric?</button>
Or, when pulling input from a form:
<script type="text/javascript">
//get the form input
var age = document.getElementById('age').value;
//check if age is a number
if(form_input_is_numeric(age)){
alert("Your age is numeric!");
}
else{
alert("Your age is not numeric...");
}
</script>
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.
