In this blog post you’ll learn how to create input field that accept only numeric values or numbers using JavaScript. We’ll see different approaches to achieve this functionality.
JavaScript method used:
Search()replace()
isNaN()
slice()
Allow Only Number in Input Field.
First, let's create the basic design for input fields using HTML and CSS.
HTML
<!DOCTYPE html>
<html lang="en">
<!-- maketechstuff.com -->
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Make input field that only allow numbers. | Maketechstuff.com</title>
</head>
<style>
*{
padding: 0px;
margin: 0px;
}
body {
width: 100%;
height: 100vh;
background: linear-gradient(45deg, #f11fdb, #613ddb);;
}
.container{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50% , -50%);
width: 400px;
padding: 20px;
border: 1px solid #fff;
}
.input_box{
width: 100%;
display: inline-flex;
}
input{
width: 100%;
font-size: 25px;
padding: 10px;
}
p{
font-size: 20px;
color: #fff;
}
</style>
<body>
<div class="container">
<h2 style="text-align: center; font-size: 30px; color: #fff; margin-bottom: 30px;">Maketechstuff.com</h2>
<div class="input_box">
<input type="text" class="input">
</div>
<p class="message"></p>
</div>
</body>
</html>
CSS
*{
padding: 0px;
margin: 0px;
}
body {
width: 100%;
height: 100vh;
background: linear-gradient(45deg, #f11fdb, #613ddb);;
}
.container{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50% , -50%);
width: 400px;
padding: 20px;
border: 1px solid #fff;
}
.input_box{
width: 100%;
display: inline-flex;
}
input{
width: 100%;
font-size: 25px;
padding: 10px;
}
p{
font-size: 20px;
color: #fff;
}
Output:
Once the basic design is created, let's add JavaScript for input field functionality to accept only numbers. We'll see two approaches.
A simple number-only input field functionality can be achieved by simply replacing the non numeric values. Like this:
JavaScript
let input_field = document.querySelector(".input");
let message = document.querySelector(".message");
input_field.addEventListener("input", maketechstuff);
function maketechstuff(){
input_field.value = input_field.value.replace(/[^0-9]/, "");
}
If you want to inform users that the input field only accepts numbers When they enter the non-numeric value, then you should add some conditions. These conditions will prevent invalid input (non-numeric input) from being entered and display a clear message indicating that only numbers are allowed.
Approach 1: Combining of search() and replace() Methods.
In this approach we’ll use the search() method along with regular expressions to identify non-numeric characters in the input field. The search() method returns the index of the first non-numeric character found, or -1 if the string contains only numbers.
If the search() method doesn't return -1, it indicates the presence of non-numeric characters. In this case, we use an if statement to replace those characters with an empty string ("") (with replace() method) and display an error message that "Only numbers are allowed.".
And, if the search() method returns -1, Means the absence of non-numeric characters, then we remove the error message.
This process is continuously executed on input events, ensuring real-time validation.
See the below code.
JavaScript
let input_field = document.querySelector(".input");
let message = document.querySelector(".message");
input_field.addEventListener("input", maketechstuff);
function maketechstuff(){
let i = input_field.value.search(/[^0-9]/);
console.log(i);
if(i != -1){
input_field.value = input_field.value.replace(/[^0-9]/, "");
message.innerHTML = "Only numbers can be accepted.";
}else{
message.innerHTML = "";
}
}
Output:
Approach 2: Combining of isNaN() and slice() Methods.
The isNaN() method (is-not-a-number) checks if a value is not a number and returns True if it is, and False otherwise.
We use an if statement to check the condition. If the condition is True, it means the value is not a number. In this case, we use the slice() method to set the input field value to the previous valid value (the value before the non-numeric characters were entered) and display an error message that “only numbers are allowed”. If the value is a number, we simply hide the error message.
We store this entire process in a function and call on input events in the input field.
See the below code
JavaScript
let input_field = document.querySelector(".input");
let message = document.querySelector(".message");
input_field.addEventListener("input", maketechstuff);
function maketechstuff(){
if(isNaN(input_field.value)){
input_field.value = input_field.value.slice(0, input_field.value.length-1);
message.innerHTML = "Only numbers can be accepted.";
}else{
message.innerHTML = "";
}
}
Output:
Approach 3: Combining of for loop and match() Methods.
First, we split the input field value into an array of characters using the split method.
Then, we check each item in the array to see if it is not an number.
If the item is not one numeric character, we leave the input field value unchanged (as previous before entering the non allowed characters) and display a message stating that "only numeric values are allowed."
If the item is an numeric character, we simply remove the message.
We store this entire process in a function and call on input events in the input field.
See the below code.
JavaScript
let input_field = document.querySelector(".input");
let message = document.querySelector(".message");
input_field.addEventListener("input", maketechstuff);
function maketechstuff() {
let array = input_field.value.split("");
for (let i = 0; i < array.length; i++) {
const element = array[i];
if (!element.match(/[0-9]/)) {
message.innerHTML = "Only numeric values are allowed.";
input_field.value = input_field.value.slice(0, input_field.value.length - 1);
} else {
message.innerHTML = "";
}
}
}
This is how you can create an input field that only allows numeric input using JavaScript. If you have any questions or suggestions, feel free to leave them in the comment section below.
You may like:
- How to create a 4-digit OTP input field using HTML CSS and JavaScript.
- Create input field that allows only alphanumeric values using JavaScript.
- How to animate the input field on focus using HTML and CSS.
- How to type in two input field simultaneously using JavaScript.
- How to add image inside input field using HTML and CSS.
- How to check input field is empty or not using JavaScript.
- Highlight input field on focus using HTMLCSS and JavaScript.
- Automatic change the case of input field value on input using JavaScript.
Share your thoughts.