To validate an input box value for only integer type in JavaScript, you can use the parseInt()
function or a regular expression to check whether the input contains only digits. Here are two common methods to achieve this:
Method 1: Using parseInt()
function validateInput() {
var inputValue = document.getElementById("inputBox").value;
if (inputValue === "") {
alert("Please enter a value.");
return false;
}
if (parseInt(inputValue) != inputValue) {
alert("Please enter a valid integer.");
return false;
}
// Input is a valid integer
return true;
}
In this method, parseInt()
attempts to parse the input value as an integer. If the input contains non-numeric characters or a floating-point number, parseInt()
will return a different value than the original input.
Method 2: Using Regular Expression
function validateInput() {
var inputValue = document.getElementById("inputBox").value;
var integerPattern = /^\d+$/;
if (inputValue === "") {
alert("Please enter a value.");
return false;
}
if (!integerPattern.test(inputValue)) {
alert("Please enter a valid integer.");
return false;
}
// Input is a valid integer
return true;
}
In this method, a regular expression (/^\d+$/
) is used to test whether the input consists only of digits (0-9). If the input contains any non-digit characters, the test will fail, and the function will return false
.
HTML Input Element
<input type="text" id="inputBox">
<button onclick="validateInput()">Submit</button>
In both methods, the validateInput()
function is called when the user clicks the submit button. Adjust the function names and input element IDs to match your specific use case.
Brijpal Sharma is a web developer with a passion for writing tech tutorials. Learn JavaScript and other web development technology.