I am making a simple email sender and what I want to do is to check if the textbox.text has 14 characters. If it's 14 - then text turns to green, if less it turns to red. I've encountered a problem when I type 14th character. It doesn't turn green. It does when I type another character which is not shown since I have MaxLength = 14, but I still need to type in that 15th character. Also when I try deleting characters, the string doesn't turn red with the first deleted char, but after a few. I've tried things like Regex and trim() thinking that there might be some special characters but it doesn't seem to work. I also recorded a video with the issue to make it more describing.
private void trackBox1_KeyPress(object sender, KeyPressEventArgs e)
{
trackBox1.Text = RemoveSpecialCharacters(trackBox1.Text);
trackBox1.Text = trackBox1.Text.Replace("\r\n", "\n");
errorBox.Text = trackBox1.TextLength.ToString();
if (trackBox1.TextLength < 14)
{
trackBox1.ForeColor = Color.Red;
} else if (trackBox1.TextLength == 14)
{
trackBox1.ForeColor = Color.Green;
}
trackBox1.Text.TrimEnd();
}
public static string RemoveSpecialCharacters(string str)
{
return Regex.Replace(str, "[^a-zA-Z0-9_.]+", "", RegexOptions.Compiled);
}