0

How do I restrict a user from entering multiple decimals into a text box in C#? The code below is my starting point:

if (System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "[^0-9.]+")) {
    MessageBox.Show("Please enter only numbers.");
    textBox1.Text = textBox1.Text.Remove(textBox1.Text.Length - 1);
}
Don Brody
  • 1,689
  • 2
  • 18
  • 30
Mom
  • 13
  • 3
  • what do you mean multiple decimals? – Neil Mar 13 '19 at 18:02
  • for example since I am doing money forms I do not want a user to enter something like "2.2.2.2.2" etc.. I want something like "2.20" – Mom Mar 13 '19 at 18:05
  • 3
    What about using a NumericUpDown control instead of a TextBox? Proper tools for the job should be the first option – Steve Mar 13 '19 at 18:08
  • Well, the reason being is that NumericUpDown isn't part of my assignment that i need to do. – Mom Mar 13 '19 at 18:14
  • NumericUpDown may not be *the* proper tool for the job, e.g. if this is input field is for money with cents precision then NumericUpDown selection of the value $2.50 would require ~51 clicks - not ideal – MyStackRunnethOver Mar 13 '19 at 18:36
  • Hi Mom (lol) - have you seen this question? https://stackoverflow.com/questions/12117024/decimal-number-regular-expression-where-digit-after-decimal-is-optional/12117060 – MyStackRunnethOver Mar 13 '19 at 18:37
  • Please do not use a NumericUpDown for numeric data entry. That is the most annoying UX in the world. – John Wu Mar 13 '19 at 19:02
  • i figured it out. Using a NumericUpDown is mostly used for quantities but not ideal for doing money orders – Mom Mar 14 '19 at 19:33
  • also I didn't see that, i been searching the whole site for something like that. – Mom Mar 14 '19 at 19:34

1 Answers1

0

if what you are trying to prevent is input like this "0.0.0" then your regex is incorrect

^([0-9]+.?[0-9]*)$

is the expression you are looking for. [^0-9.]+ is going to be one or more number or . so "........" would match that. The '?' you want to use for the decimal since it is "Zero or One" of that character

zlb323
  • 106
  • 1
  • 7
  • When I put that in, and I tested it. Its the message box is giving me "Please only enter numbers". No matter what I put in wither that would be 1, 21.2, or 0.0.0, is just going to show that message box. – Mom Mar 13 '19 at 18:13
  • I updated it since I forgot that the regex would match any string that contained a number instead of only the number. Other than that I don't seem to be having any problems with it. try it now but reverse the boolean value of the result like "if (!System...." – zlb323 Mar 13 '19 at 18:21