


How to verify if input is alphanumeric or non-alphanumeric using JavaScript?
Our task is to validate the input string and we need to check if it is alphanumeric using JavaScript. Alphanumeric strings contain only numeric and alphabetic characters, including uppercase or lowercase characters, and not even any special characters or spaces.
Below, we will see two methods of validating input strings.
Use charCodeAt() method
We can use the charCodeAT() method to get the ASCII value of any character. Here, we will iterate through each character of the string and check the ASCII value of each character. ASCII codes between 48 and 57 represent numeric characters, 97 and 122 represent lowercase alphabetic characters, and 65 and 90 represent uppercase alphabetic characters.
So if we find any character whose ASCII value is not between the ASCII range given above, we can say that the string is not alphanumeric.
grammar
Users can use the charCodeAT() method according to the following syntax to check whether the input string is alphanumeric.
let charCode = char.charCodeAt(0); if (!(charCode > 47 && charCode < 58) && !(charCode > 96 && charCode < 123) && !(charCode > 64 && charCode < 91) ) { // string is not alphanumeric return; }
In the above syntax, char is a single character. We use the charCodeAT() method to get the ASCII value of a single character. After that, we use an if-else statement to check if the ASCII code of the character is between the ASCII values of the numeric and alphabetic characters.
Example 1
In the example below, we create two input strings containing various characters. Additionally, we define the validateString() function. In the validateString() function, we use a for-of loop to iterate over each string character. Additionally, we use the charCodeAt() method to get the ASCII value of a character by passing 0 as argument.
We then check if there is a character whose ASCII code is not between the ASCII range for numeric and alphabetic characters; we can say that the string is not alphanumeric.
<html> <body> <h3>Using the <i> for loop and charCodeAT() method </i> to check if input string is alphanumeric or not</h3> <div id = "output"> </div> <script> var output = document.getElementById('output'); let str1 = "aredsUADFSKH121342kjbrewdfv"; let str2 = "dfdrg rflrtke 435 3df;fd'gfdg"; 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 += "The string " + string + " is not alphanumeric! </br>"; return; } } output.innerHTML += "The string " + string + " is an alphanumeric! </br>"; } validateString(str1); validateString(str2); </script> </body> </html>
Use regular expressions
We can create regular expressions using the RegExp() constructor with the new keyword. It is a pattern where we can match an input string against a regular expression pattern and return a true or false boolean based on this.
grammar
Users can use regular expressions to validate alphanumeric strings according to the following syntax.
let strRegex = new RegExp(/^[a-z0-9]+$/i); let result = strRegex.test(string);
In the above syntax, the result variable contains a boolean value based on whether the string is alphanumeric.
Regular expression explanation
^ - Indicates the beginning of the string.
[a-z0-9] - Represents only characters from a to z or 0 to 9.
$ - Indicates the end of the string.
i – This is the flag for regular expressions used for case-insensitive string comparisons.
Example 2
In the following example, we call the validateString() function by passing various strings as parameters. In the function we create the normal interpretation as above. After that, we use the test() method by passing the regular expression as a reference and passing the input string as the validation parameter.
If the test() method returns true, the input string is alphanumeric and contains only numeric and alphabetic characters; otherwise, the string is not alphanumeric.
<html> <body> <h3>Using the <i> Regular expression </i> to check if input string is alphanumeric or not</h3> <div id = "output"> </div> <script> var output = document.getElementById('output'); let str1 = "Welcome to the tutorialsPoint"; let str2 = "Hello123"; function validateString(string) { // Defining the regular expression let strRegex = new RegExp(/^[a-z0-9]+$/i); // match the regex with the string let result = strRegex.test(string); if (result) { output.innerHTML += "The string " + string + " is an alphanumeric! </br>"; } else { output.innerHTML += "The string " + string + " is not alphanumeric! </br>"; } } validateString(str1); validateString(str2); </script> </body> </html>
Example 3
In the following example, we use the Prompt () method to get a string from the user. After that, we use a regular expression to validate the string, just like we used in the above example, but here we use a different regular expression.
Here, [^a-zA-Z0-9] represents any character that is not between a to z, A to Z, and 0 to 9. Therefore, the test() method returns true if the string is not alphanumeric and false for alphanumeric strings.
<html> <body> <h3>Using the <i> Regular expression </i> to check if input string is alphanumeric or not</h3> <div id = "output"> </div> <button onClick = "getInputAndValidate()"> Validate random string </button> <script> var output = document.getElementById('output'); function getInputAndValidate() { let string = prompt("Enter a string to validate", "1232dwe"); let strRegex = new RegExp(/[^a-zA-Z0-9]/); // match the regex with the string let result = strRegex.test(string); if (!result) { output.innerHTML += "The string " + string + " is an alphanumeric! </br>"; } else { output.innerHTML += "The string " + string + " is not alphanumeric! </br>"; } } </script> </body> </html>
We learned about validating alphanumeric strings in this tutorial. We use two different regular expressions to validate alphanumeric strings. Also, we have learned a simple way using for loop and charCodeAT() method, but it is not time efficient and is not recommended.
The above is the detailed content of How to verify if input is alphanumeric or non-alphanumeric using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing
