Skip to content

Instantly share code, notes, and snippets.

@o-az
Last active June 16, 2024 15:46
Show Gist options
  • Save o-az/9d304e88af9706bcc6d1cc6c3984a2f3 to your computer and use it in GitHub Desktop.
Save o-az/9d304e88af9706bcc6d1cc6c3984a2f3 to your computer and use it in GitHub Desktop.
GitHub username regex: /^[a-z\d](?:[a-z\d]|-(?=[a-z\d])){0,38}(-?)?$/i
import assert from 'node:assert'
/**
* Run with `node github-username-regex.mjs` or `npx tsx github-username-regex.mjs`
*/
/**
* 1-39 characters
* case insensitive alphanumeric + hyphen
* cannot start with hyphen
* cannot have consecutive hyphens
* cannot end with hyphen for new users, but existing usernames can
*/
const pattern = /^[a-z\d](?:[a-z\d]|-(?=[a-z\d])){0,38}(-?)?$/i
const cases = [
{ value: "", valid: false },
{ value: "u", valid: true },
{ value: "valid-username", valid: true },
{ value: "Valid-Username", valid: true },
{ value: "-invalid-username", valid: false },
{ value: "valiD-Old-Username-", valid: true },
{ value: "invalid-username--", valid: false },
{ value: "Valid-Username-123-456", valid: true },
{ value: "testingusername01testingusername01testi", valid: true },
]
for(const testCase of cases) {
const valid = pattern.test(testCase.value)
assert.strictEqual(valid, testCase.valid, `Value: ${testCase.value}`)
}
@o-az
Copy link
Author

o-az commented Jun 16, 2024

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment