-2

I have a pattern and want to empty the textbox and show a message when the input does not match the pattern.

I have tried putting the erasing line in else, and used a negation ! in front of the condition.

   if (!Regex.IsMatch(MyTextBox.Text, ".*?[0-9].*?"))
   {
       MyTextBox.Text = "";
       MessageBox.Show("Please input only numbers");
   }

But both of these solution result in that if ANY symbol in the textbox matches the pattern gives an error when I want to float.parse the string later on.

Examples:

  • 1234 should and does work
  • A Stops you as it should
  • 1A Doesn't stop you, but should
Diggy
  • 1
  • 2
  • Just use `float.TryParse()` instead. You don't need to validate it manually and then use `float.Parse()` later on. – Broots Waymb Jan 15 '21 at 18:46
  • You could also just add type='number' to your input element, this would force this behavior without the need for the validation or message. https://stackoverflow.com/a/33755754/3845625 – Zabbu Jan 15 '21 at 21:27

1 Answers1

1

Try to use this:

if (!Regex.IsMatch(textbox.Text, "^[0-9]*$")){
....
}
Serge
  • 40,935
  • 4
  • 18
  • 45