I wanted to make a TextChanged event that would check to see whether the input text fit a particular criteria, and remove the last character entered if it did not. In this case, the criteria is numbers, 1 decimal, and 1 fraction.
I was testing a regex just for numbers and a decimal and ran into an issue. I've tried several different expressions (I'm terrible at writing my own, so they are picked up from various other stack overflow questions), and the result is the same every time. It accepts numbers just fine, but it doesn't accept decimals. Any help would be greatly appreciated!
string isNumber = @"^\d{1,9}(\.\d{1,9})?$";
private void TextBox_TextChanged(object sender, EventArgs e)
{
TextBox text = (TextBox)sender;
Match match = Regex.Match(text.Text, isNumber);
if (!match.Success)
{
if (text.Text.Length > 1)
text.Text = text.Text.Substring(0, text.Text.Length - 1);
else
text.Text = "";
text.Select(text.Text.Length, 0); //set cursor to the end
//of the string
}
}
I think the problem is that you are trying to validate the number character-by-character as the user types, but it is not possible to type a valid decimal number without the value being an invalid value temporarily.
Consider what happens as the user types the value 1.2
:
1
. 1
is a valid decimal, so validation passes..
1.
is not a valid decimal according to the regular expression, so the last character is erased.1
.As you can see, it's not possible to enter the decimal point. But, if you try to change your regular expression to allow a decimal point to exist without a following digit, then you could have an invalid value if the user stops after typing the decimal point and then submits the form.
So the point is, using a character-by-character validation scheme will not work for decimals. A better approach would be to allow the user to enter whatever they want in the box and then validate later when the user is finished typing. You can do this by validating when the textbox loses focus or when the form is submitted.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With