Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 3rd, 2012  |  syntax: None  |  size: 1.50 KB  |  hits: 18  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Validate float number using RegEx in C#
  2. void NumericTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
  3. {
  4.     e.Handled = !IsValidInput(e.Text);
  5. }
  6.  
  7. private bool IsValidInput(string p)
  8. {
  9.     switch (this.Type)
  10.     {
  11.         case NumericTextBoxType.Float:
  12.             return Regex.Match(p, "^[0-9]*[.][0-9]*$").Success;
  13.         case NumericTextBoxType.Integer:                    
  14.         default:
  15.             return Regex.Match(p, "^[0-9]*$").Success;                    
  16.     }
  17. }
  18.  
  19. // And also this!
  20. public enum NumericTextBoxType
  21. {
  22.     Integer = 0,
  23.     Float = 1
  24. }
  25.        
  26. @"^[0-9]*(?:.[0-9]*)?$"
  27.        
  28. var regex = new Regex(@"^[0-9]*(?:.[0-9]*)?$");
  29. Console.WriteLine(new bool[] {regex.IsMatch("blah"),
  30.                               regex.IsMatch("12"),
  31.                               regex.IsMatch(".3"),
  32.                               regex.IsMatch("12.3"),
  33.                               regex.IsMatch("12.3.4")});
  34.        
  35. False
  36. True
  37. True
  38. True
  39. False
  40.        
  41. private bool IsValidInput(string p)
  42. {
  43.     switch (this.Type)
  44.     {
  45.         case NumericTextBoxType.Float:
  46.             double doubleResult;
  47.             return double.TryParse(p, out doubleResult);
  48.         case NumericTextBoxType.Integer:                    
  49.         default:
  50.             int intResult;
  51.             return int.TryParse(p, out intResult);
  52.     }
  53. }
  54.        
  55. public static double? TryParseInt(this string source)
  56. {
  57.     double result;
  58.     return double.TryParse(source, out result) ? result : (double?)null;
  59. }
  60.  
  61. // usage
  62. bool ok = source.TryParseInt().HasValue;