Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

isAlphanumeric

Checks if a string contains only letters and numbers (A–Z, a–z, 0–9).

TypeScript
Copied!
1/**
2 * Checks if a string contains only letters and numbers (A–Z, a–z, 0–9).
3 *
4 * @param str - The string to validate.
5 * @returns True if the string is alphanumeric, false otherwise.
6 */
7export function isAlphanumeric(str: string): boolean {
8  return /^[A-Za-z0-9]+$/.test(str);
9}
  • Fast and Lightweight

    Performs validation with a single regular expression — no external dependencies or heavy parsing logic.

  • Strict Format Enforcement

    Ensures the string consists only of letters and numbers, rejecting any punctuation, spaces, or symbols.

  • Consistent Behavior Across Browsers

    Uses standard JavaScript regex, guaranteeing predictable results in all environments.

  • Reusable Utility

    Easy to integrate into both client-side and server-side validation pipelines.

Tests | Examples

TypeScript
Copied!
1test('isAlphanumeric - valid alphanumeric strings', () => {
2  expect(isAlphanumeric('abc123')).toBe(true);
3  expect(isAlphanumeric('ABC')).toBe(true);
4  expect(isAlphanumeric('123456')).toBe(true);
5});
6
7test('isAlphanumeric - invalid strings with symbols or spaces', () => {
8  expect(isAlphanumeric('abc123!')).toBe(false);
9  expect(isAlphanumeric('hello world')).toBe(false);
10  expect(isAlphanumeric('')).toBe(false);
11});

Common Use Cases

  • Username Validation

    Enforce simple, secure, and readable usernames without special characters.

  • Coupon or Promo Code Checks

    Validate alphanumeric-only codes submitted by users or generated programmatically.

  • Form Field Sanitization

    Ensure certain fields (e.g. IDs, labels, product SKUs) do not contain invalid characters.

  • Password Policy Checks (Basic)

    Enforce that a password includes only letters and digits for legacy systems or simple policies.

Codebase: Utilities -> Validation -> isAlphanumeric | Yevhen Klymentiev