How to validate an input is alphanumeric or not using JavaScript?

Validating whether an input contains only alphanumeric characters (letters and numbers, no spaces or special characters) is a common requirement in JavaScript applications. An alphanumeric string contains only numeric digits (0-9) and alphabetical characters (A-Z, a-z).

Below are two effective approaches to validate alphanumeric strings in JavaScript.

Using the charCodeAt() Method

The charCodeAt() method returns the ASCII value of a character. We can iterate through each character and check if its ASCII value falls within the valid ranges:

  • 48-57: Numeric characters (0-9)

  • 65-90: Uppercase letters (A-Z)

  • 97-122: Lowercase letters (a-z)

Syntax

let charCode = char.charCodeAt(0);
if (!(charCode > 47 && charCode < 58) &&
    !(charCode > 96 && charCode < 123) &&
    !(charCode > 64 && charCode < 91)) {
    // Character is not alphanumeric
    return false;
}

Example

<html>
<body>
    <h3>Using <i>charCodeAt() method</i> to validate alphanumeric strings</h3>
    <div id="output"></div>
    <script>
        var output = document.getElementById('output');
        let str1 = "Hello123World";
        let str2 = "Hello 123!";
        
        function validateString(string) {
            for (let char of string) {
                let charCode = char.charCodeAt(0);
                if (!(charCode > 47 && charCode < 58) &&
                    !(charCode > 96 && charCode < 123) &&
                    !(charCode > 64 && charCode < 91)) {
                    output.innerHTML += "'" + string + "' is NOT alphanumeric<br>";
                    return;
                }
            }
            output.innerHTML += "'" + string + "' is alphanumeric<br>";
        }
        
        validateString(str1);
        validateString(str2);
    </script>
</body>
</html>

Using Regular Expressions (Recommended)

Regular expressions provide a more concise and efficient way to validate alphanumeric strings. The pattern /^[a-z0-9]+$/i matches strings containing only letters and numbers.

Syntax

let regex = /^[a-z0-9]+$/i;
let isAlphanumeric = regex.test(string);

Regular Expression Breakdown

  • ^ - Start of string anchor

  • [a-z0-9]+ - One or more letters (a-z) or digits (0-9)

  • $ - End of string anchor

  • i - Case-insensitive flag

Example with Positive Matching

<html>
<body>
    <h3>Using <i>Regular Expression</i> to validate alphanumeric strings</h3>
    <div id="output"></div>
    <script>
        var output = document.getElementById('output');
        let testStrings = ["Hello123", "Test String", "ABC123xyz", "Hello@World"];
        
        function validateString(string) {
            let regex = /^[a-z0-9]+$/i;
            let isValid = regex.test(string);
            
            if (isValid) {
                output.innerHTML += "'" + string + "' is alphanumeric<br>";
            } else {
                output.innerHTML += "'" + string + "' is NOT alphanumeric<br>";
            }
        }
        
        testStrings.forEach(str => validateString(str));
    </script>
</body>
</html>

Example with Negative Matching

<html>
<body>
    <h3>Using <i>Negative Regular Expression</i> to detect non-alphanumeric characters</h3>
    <div id="output"></div>
    <button onclick="getInputAndValidate()">Test Custom Input</button>
    <script>
        var output = document.getElementById('output');
        
        function getInputAndValidate() {
            let string = prompt("Enter a string to validate:", "Test123");
            if (string === null) return;
            
            // This regex matches any non-alphanumeric character
            let regex = /[^a-zA-Z0-9]/;
            let hasNonAlphanumeric = regex.test(string);
            
            if (!hasNonAlphanumeric) {
                output.innerHTML += "'" + string + "' is alphanumeric<br>";
            } else {
                output.innerHTML += "'" + string + "' contains non-alphanumeric characters<br>";
            }
        }
    </script>
</body>
</html>

Comparison of Methods

Method Performance Readability Recommended
charCodeAt() with loop Slower for long strings More verbose No
Regular Expression Faster and optimized Concise and clear Yes

Conclusion

Regular expressions provide the most efficient and readable solution for alphanumeric validation. Use /^[a-z0-9]+$/i for positive matching or /[^a-zA-Z0-9]/ for detecting invalid characters. The charCodeAt() approach works but is less efficient for production use.

Updated on: 2026-03-15T23:19:00+05:30

12K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements