cybersecurity · intermediate · ~15 min

Validate a username

Enforce an allowlist + length on input.

Challenge

Validate a username with a strict character allowlist and a length bound.

Task

Implement int valid_username(const char *s) that returns 1 if s is acceptable, else 0.

s is valid when it is 1..32 characters long and every character is a letter, digit, or underscore.

Input

  • s: a NUL-terminated candidate username the grader passes.

Output

Returns int: 1 if valid, else 0.

Example

valid_username("alice_99")   ->   1
valid_username("")           ->   0   (empty)
valid_username("a b")        ->   0   (space not allowed)

Edge cases

  • The empty string is invalid (minimum length 1).
  • Any character outside [A-Za-z0-9_] rejects the whole string.

Rules

  • Allowlist the valid characters rather than blocklisting bad ones.

Input format

A NUL-terminated candidate username s.

Output format

An int: 1 if s is 1..32 chars of [A-Za-z0-9_], else 0.

Constraints

Allowlist [A-Za-z0-9_]; length 1..32; empty is invalid.

Starter code

int valid_username(const char *s) {
    /* TODO */
    return 0;
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.