Alphanumeric Validation Regular Expression
Alphanumeric validation ensures that input contains only letters (A-Z, a-z) and digits (0-9). This is commonly used for usernames, identifiers, product codes, and other fields where only basic ASCII letters and numbers are permitted. The pattern strictly validates ASCII characters and does not support Unicode letters, accented characters, or special symbols.
Recommended Solution
Explanation
^- Start of the string.[a-zA-Z0-9]+- Matches one or more characters that are either uppercase letters (A-Z), lowercase letters (a-z), or digits (0-9).$- End of the string.
Note: This pattern uses ASCII character ranges and does not support Unicode characters. If you need to support international characters (e.g., ñ, é, 你, Ж), consider using Unicode character classes like \p{L} and \p{N} where supported, or a more permissive pattern.
Implementation
Test Cases
| Input | Valid |
|---|---|
| abc123 | |
| ABC | |
| 123 | |
| Test123 | |
| a1b2c3 | |
| 0 | |
| Z | |
| (empty string) | |
| abc-123 | |
| abc_123 | |
| abc 123 | |
| abc.123 | |
| abc@123 | |
| hello world | |
| test! | |
| user@domain | |
| ñoño | |
| café | |
| 你好 | |
| привет |
With Underscores
For cases where you need to allow underscores in addition to letters and numbers (common for programming identifiers, variable names, or database column names), you can use this extended pattern. This is useful for validating usernames, API keys, or any identifier that follows programming language naming conventions.
Explanation
^- Start of the string.[a-zA-Z0-9_]+- Matches one or more characters that are uppercase letters (A-Z), lowercase letters (a-z), digits (0-9), or underscores (_).$- End of the string.
Alternative: You can also use the shorthand \w which is equivalent to [a-zA-Z0-9_] in most regex flavors, making the pattern ^\w+$. However, be aware that in some environments (like JavaScript with Unicode flag), \w may match additional Unicode characters.
Implementation
Test Cases
| Input | Valid |
|---|---|
| abc123 | |
| ABC | |
| 123 | |
| Test123 | |
| a1b2c3 | |
| 0 | |
| Z | |
| abc_123 | |
| user_name_123 | |
| TEST_CONSTANT | |
| (empty string) | |
| abc-123 | |
| abc 123 | |
| abc.123 | |
| abc@123 | |
| hello world | |
| test! | |
| user@domain | |
| ñoño | |
| café | |
| 你好 | |
| привет |