I have a TextBox where I want to let users enter hexadecimal values (excluding the 0x prefix) in a comma separated list. The problem is that I only want each value to be a length of four characters. Following this answer, I use the KeyPress event handler to do this check that the user can only enter a digit:
private void filterIDTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (!Char.IsControl(e.KeyChar) && !Char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
With Regex, we can restrict the user even more to only allow 0-9, A-F, a-f, and comma like this:
private void filterIDTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (!Char.IsControl(e.KeyChar) && !Regex.IsMatch(e.KeyChar.ToString(), "[0-9A-Fa-f,]"))
{
e.Handled = true;
}
}
Is there any way I can use regex to make sure there are no more than 4 characters in between each comma? I tried using "[0-9A-Fa-f,]{0:4}"
but this didn't work because I am doing the match only on the char, not the TextBox's text.
With that, I'm sure I'll have to use something other than KeyPress
, but I still have been unsuccessful in writing the Regex statement for only allowing values up to 4 characters.