CodersTechZone
  • .NET
    • C#
    • ASP.Net
  • HTML
  • Javascript
  • CSS
  • Database
    • SQL Server
    • MYSql
    • Oracle
  • AI
  • TechNews
  • Web-Stories

IsAlphanumeric JavaScript: Fix Your Validation Issues Fast!

Shawpnendu Bikash Maloroy

August 17, 2024
IsAlphanumeric JavaScript - Fix Your Validation Issues Fast
Spread the love

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

  • What is Alphanumeric?
  • Why We Use isAlphanumeric?
  • Basic Method to Check if a String is Alphanumeric
  • Output – isalphanumeric javascript Method
  • Code Explanation
  • Using Character Codes to Check Alphanumeric
  • Output
  • Code Explanation
  • Practical Use Cases
  • Full Example: Validating Form Input
  • Output
  • Code Explanation
  • Summary Table
  • Conclusion

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

isalphanumeric javascript - Using basic JS method
isalphanumeric javascript – Using basic JS method
buymeacoffee

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

isalphanumeric javascript - Using Character Code
isalphanumeric javascript – Using Character Code
buymeacoffee

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

isalphanumeric javascript – complete code example

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

MethodCode Example
Regular Expression/^[a-z0-9]+$/i.test(str)
Character CodescharCodeAt(i)
Combined MethodYou 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!

Shawpnendu Bikash Maloroy
Shawpnendu Bikash Maloroy

🏋️‍♂️ Discover Code Blocks From 20+ yrs JS Expert
💥 Asp.net C# Developer
🏆 Solution Architect
👨‍✈️ Database Administrator
📢 Speaker
🎓 MCTS since 2009

Share this:

  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on X (Opens in new window) X

Spread the love
«Previous
Next»

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • 5 Lesser-Known JavaScript Functions
    5 Lesser-Known JavaScript Functions to Boost Your Coding Efficiency
  • 7 Weird JavaScript Tricks That Look Like Bugs
    7 Weird JavaScript Tricks That Look Like Bugs (#3 Will Shock You!)
  • Build a JavaScript Gamer Journal in 8 Lines
    🎮 Build a JavaScript Gamer Journal in 8 Lines: Track Your Wins Like a Pro! 🏆
  • JavaScript Pet Feeder Reminder in 7 Lines
    How to Code a Simple JavaScript Pet Feeder Reminder in 7 Lines: Feed Your Pet Like a Coding Boss! 🐶
  • 10-line calculator JavaScript
    Build a Simple Calculator in JavaScript: 10 Lines to Wow Your Friends!

About-CodersTech Zone |  Contact |  Disclaimer |  Fact-Checking policy |  Affiliate Disclosure |  Privacy Policy

Copyright © 2024 CodersTechZone.com