Skip to content

Instantly share code, notes, and snippets.

@Laiteux
Last active May 12, 2024 08:52
Show Gist options
  • Save Laiteux/bc6895e8e3dcfe7ffaa91cf2c1077031 to your computer and use it in GitHub Desktop.
Save Laiteux/bc6895e8e3dcfe7ffaa91cf2c1077031 to your computer and use it in GitHub Desktop.
C# method to validate a Telegram username using RegEx
using System;
using System.Text.RegularExpressions;
// NOTE: Change min length to 4 (instead of 5) in the RegEx if you want to include/allow NFT/Fragment usernames
bool ValidateTelegramUsername(string username)
=> Regex.IsMatch(username.TrimStart('@'),
@"^(?=.{5,32}$)(?!.*__)(?!^(telegram|admin|support))[a-z][a-z0-9_]*[a-z0-9]$",
RegexOptions.IgnoreCase | RegexOptions.Compiled);
Console.WriteLine(ValidateTelegramUsername("Laiteux1")); // True
Console.WriteLine(ValidateTelegramUsername("1Laiteux")); // False: Must start with a letter
Console.WriteLine(ValidateTelegramUsername("Lait")); // False: Too short (must contain between 5 and 32 characters)
Console.WriteLine(ValidateTelegramUsername("_Laiteux_")); // False: Starts or ends with an underscore
Console.WriteLine(ValidateTelegramUsername("Lait__eux")); // False: Contains two or more consecutive underscores
Console.WriteLine(ValidateTelegramUsername("AdminLaiteux")); // False: Starts with "Telegram", "Admin" or "Support"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment