In this blog post, you'll learn how to create input fields that accept only alphanumeric values (letters and numbers) using JavaScript. We'll explore different approaches to achieve this functionality.
JavaScript Method Used:
Search()
replace()
Match()
And we also use a For loop.
Allow Only Alphanumeric value 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 accept only alphanumeric values. | Maketechstuff.com</title>
</head>
<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 alpha-numeric values. We'll see two approaches.
A simple alpha-numeric value input field functionality can be achieved by simply replacing the non-alpha-numeric values with empty string (“”). Like this:
JavaScript
let input_field = document.querySelector(".input");
let message = document.querySelector(".message");
input_field.addEventListener("input", maketechstuff);
// simple way:
function maketechstuff() {
input_field.value = input_field.value.replace(/[^\.\sa-zA-Z0-9]/, "");
}
As you can see, I've used a regular expression here. It replaces non-alphanumeric characters, including spaces and periods (dots). However, this also removes spaces and periods that we want to keep. Therefore, we need to modify the regular expression to only replace non-alphanumeric characters, while preserving spaces and periods."
/[^\.\sa-zA-Z0-9]/
This regular expression checks for any values other than alphabets (uppercase and lowercase), numbers, dots, and spaces.
We also inform users with messages that the input field only accepts alphabets (uppercase and lowercase), numbers, dots, and spaces, If they enter the characters other than alphabets (uppercase and lowercase), numbers, dots, and spaces. we will use if statements to display a message accordingly.
Let's create the input field functionality to accept only alphabets (uppercase and lowercase), numbers, dots, and spaces.
Approach 1: Combining of search() and replace() Methods.
This approach uses the search() method and regular expressions to identify characters in the input field that are not alphanumeric (uppercase and lowercase letters, numbers), dot, and spaces.
The search() method returns the index of the first character that doesn't belong to this category; otherwise, it returns -1.
Here, If the search() method returns a value other than -1, it indicates the presence of non-alphanumeric characters, dots, and spaces. In this case, with if statement we’ll replaces these characters with an empty string ("") using the replace() method, and display the message that: "Only alphanumeric characters, dots, and spaces are allowed."
If the search() method returns -1, it signifies the absence of non-alphanumeric characters, dots, or spaces. In this case, we’ll remove any existing 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(/[^\.\sa-zA-Z0-9]/);
console.log(i);
if(i != -1){
input_field.value = input_field.value.replace(/[^\.\sa-zA-Z0-9]/, "");
message.innerHTML = "Only alphanumeric values, space and dot can be accepted.";
}else{
message.innerHTML = "";
}
}
Output:
Approach 2: 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 alphabet (uppercase or lowercase), number, dot, or space.
(Characters allowed are alphabet (uppercase or lowercase), number, dot, or space.)
If the item is not one of these allowed characters, we leave the input field value unchanged (as previous before entering the non allowed characters) and display a message stating that "only alphanumeric values (uppercase and lowercase), dots, and spaces are allowed."
If the item is an allowed 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(/[\.\sa-zA-Z0-9]/)) {
message.innerHTML = "Only alphanumeric values, space and dot can be accepted.";
input_field.value = input_field.value.slice(0, input_field.value.length - 1);
} else {
message.innerHTML = "";
}
}
}
Output:
This is how you can create an input field that only allows alphanumeric values inputs using JavaScript. If you have any questions or suggestions, feel free to leave them in the comment section below.
You may like:
- Create input field that allow only numeric values using JavaScript.
- Create input field that convert the text cases (upper and lower) instantly on user input with JavaScript
- Create OTP input fields with auto shift focus functionality on input.
- Create the input field with border animation when focus using HTML and CSS.
- Highlight the input field when focus using HTML CSS and JavaScript.
- Create input field that display the button only when it has values.
- How to add icon or image inside input field using HTML and CSS.
- Placeholder animation on focus on input field using HTML and CSS.
- Get the input field value on click with JavaScript.
- Check the input field is empty or not using JavaScript.
- Disable input dynamically using JavaScript.
Share your thoughts.