JavaScript is_int function
There isn't a JavaScript is_int() function built in to JavaScript. However, you can copy and paste this into your JavaScript and use it just like you would in PHP:
The Function
<script type="text/javascript">
function is_int(input){
return typeof(input)=='number'&&parseInt(input)==input;
}
</script>
Warning! is_int() 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_int(input){
return !isNaN(input)&&parseInt(input)==input;
}
</script>
Using is_int
Using is_int() is easy. Just call it on an input the same as you would in PHP. In this example, we check if the variable age is an int:
<script type="text/javascript">
//is age a number?
if(is_int(age)){
alert("Your age is an int!");
} else {
alert("Your age is not an int...");
}
</script>
Using form_input_is_int()
Use form_input_is_int() when validating form input. For example:
<input type="text" id="testinput" />
<button onclick="alert(form_input_is_int(document.getElementById('testinput').value))">Is it an int?</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 an int
if(form_input_is_int(age)){
alert("Your age is an int!");
}
else{
alert("Your age is not an int...");
}
</script>
Code Explanation
is_int() is a really easy function.
The typeof() function accepts any input and will return that input's type. So, we need to be sure that the type of our input is 'number'.
The parseInt() function takes any input and returns only the integer value. So, parseInt(4.12) == 4. Therefore, if parseInt(input) == input, that means input is an int.
In form_input_is_int() we also use the JavaScript function isNaN(). NaN stands for "Not a Number". So, if the input is not a number, isNaN() returns true.
