7/20/2021

C# Regular Expression - Windows Form Application (Username Validation)

 

C# Regular Expression - Windows Form Application (Username Validation)
C# Regular Expression - Windows Form Application (Username Validation)


   private void txtUsername_TextChanged(object sender, EventArgs e)
        {
            if (IsValidUsername(txtUsername.Text))
            {
                lblMsg.ForeColor = System.Drawing.Color.Green;
                lblMsg.Text = "Valid Username";
            }
            else
            {
                lblMsg.ForeColor = System.Drawing.Color.Red;
                lblMsg.Text = "Invalid Username!";
            }
        }
        public static bool IsValidUsername(string username)
        {
            //Username starts with a letter, allow letter or number, length between 7 to 12.
            string pattern;
            pattern = @"^[a-zA-Z][a-zA-Z0-9]{6,11}$";
            Regex regex = new Regex(pattern);
            return regex.IsMatch(username);
        }