As a JS developer, more often we need to check if a string is alphanumeric (contains only letters and numbers) or not. The isalphanumeric javascript method checking is very required for form validation, user input verification, and ensuring data integrity.
Table of Contents
Here in this post, I am going to explore different methods to build an isAlphanumeric function in JavaScript. I will try my best to keep all of my code examples and explanations very simple and easy to understand so that anyone can use this type of checking easily.
What is Alphanumeric?
An alphanumeric string contains only letters (A-Z, a-z) and numbers (0-9). It does not include special characters or spaces. For example, “xyz123” is alphanumeric, while “xyz123!” is not. Because “!” is a special character.
Why We Use isAlphanumeric?
Using isAlphanumeric helps to:
- Validate User Input: Ensure that input fields contain only letters and numbers.
- Sanitize Data: Remove unwanted characters from strings. Specially while processing API response.
- Improve Security: Prevent injection attacks by restricting input to alphanumeric characters.
Basic Method to Check if a String is Alphanumeric
Let’s start to create an isAlphanumeric function in JavaScript using basic method. The best solution is to use regular expressions. Regular expressions help us to define specific patterns to match strings as per our requirement.
<script>
function isAlphanumeric(str) {
const pattern = /^[a-z0-9]+$/i;
return pattern.test(str);
}
// Test the isAlphanumeric function
console.log(isAlphanumeric("xyz123")); // true
console.log(isAlphanumeric("xyz123!")); // false
</script>
Output – isalphanumeric javascript Method
Code Explanation
The used regular expression ^[a-z0-9]+$ is the pattern to check alphanumeric characters in a string.
- ^ indicates the start of the string.
- [a-z0-9] matches any letter or number.
- + ensures one or more characters are matched.
- $ indicates the end of the string.
- i makes the pattern case-insensitive.
Using Character Codes to Check Alphanumeric
Another approach we can use to implement the isAlphanumeric function in JavaScript is by checking all character codes. To do that, we need to iterate each character of the string and check if it’s character code is in the alphanumeric range or not.
<script>
function isAlphanumeric(str) {
for (let i = 0; i < str.length; i++) {
const code = str.charCodeAt(i);
if (!(code > 47 && code < 58) && // numeric (0-9)
!(code > 64 && code < 91) && // upper alpha (A-Z)
!(code > 96 && code < 123)) { // lower alpha (a-z)
return false;
}
}
return true;
}
// Test the function
console.log("xyz123="+isAlphanumeric("xyz123")); // true
console.log("xyz123!="+isAlphanumeric("xyz123!")); // false
</script>
Output
Code Explanation
To check character code, we used the charCodeAt method. The charCodeAt(i) returns the Unicode value of a character positioned at index i.
- 47 < code < 58 checks for numbers (0-9).
- 64 < code < 91 checks for uppercase letters (A-Z).
- 96 < code < 123 checks for lowercase letters (a-z).
Practical Use Cases
Here are some common scenarios where you need to use the isAlphanumeric function in JavaScript:
- Form Validation: Check whether username and password fields contain only alphanumeric characters.
- Data Filtering: Clean up user input to remove unwanted characters. Otherwise, it may raise a security risk.
- Search Filters: Allow only alphanumeric characters in search queries. Otherwise, it may raise a security risk.
Full Example: Validating Form Input
Now it’s time to create a full example to build an isAlphanumeric function to validate a form input.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>isAlphanumeric Javascript code Example</title>
</head>
<body>
<form id="myForm">
<label for="username">Username:</label>
<input type="text" id="username" name="username">
<button type="submit">Submit</button>
</form>
<script>
document.getElementById('myForm').addEventListener('submit', function(event) {
const username = document.getElementById('username').value;
if (!isAlphanumeric(username)) {
alert('Username must be alphanumeric!');
event.preventDefault();
}
});
function isAlphanumeric(str) {
const pattern = /^[a-z0-9]+$/i;
return pattern.test(str);
}
</script>
</body>
</html>
Output
Code Explanation
The submit event listener is used to check the username field text contents when the user submit the form. You can also add click event listener without using HTML elements inline onClick event.
If the function isAlphanumeric returns false means not alphanumeric then an alert is displayed and also prevented the form submission using the event.preventDefault() method. Else the form submitted successfully.
Summary Table
Method | Code Example |
Regular Expression | /^[a-z0-9]+$/i.test(str) |
Character Codes | charCodeAt(i) |
Combined Method | You can also combines both approaches as enhancement |
Conclusion
Using isAlphanumeric in JavaScript is very important for validating and filtering user input for security reasons. It’s an industry standard of good practices that we must follow. If you can understand and implement the methods as per the provided examples in this post, you can make sure your applications can check alphanumeric data validation correctly.
You can use regular expressions or character codes, whatever you like to implement your own IsAlphanumeric JavaScript Method. The key is to validate input efficiently and accurately. Happy coding!
🏋️♂️ Discover Code Blocks From 20+ yrs JS Expert
💥 Asp.net C# Developer
🏆 Solution Architect
👨✈️ Database Administrator
📢 Speaker
🎓 MCTS since 2009
Leave a Reply