Anders
Anders

Reputation: 12560

WPF Filter Textbox Input with Decimals C#

I have successfully filtered out anything but digits with the following code. I have utilized the PreviewTextInput event to capture the current input:

private void NumericValidation(object sender, TextCompositionEventArgs e)
{
    e.Handled = !_numericValidator.IsMatch(e.Text);
}

_numericValidator is defined as _numericValidator = new Regex("^[0-9]+$");

This code works perfectly fine to only allow 0-9 to be entered into the textbox.

However, I am looking to allow a single decimal so input can be more precise. I have tested the following regex in RegexBuddy and it works as I expect it should but I can input invalid numbers such as 1..1 and 4.3.5 into the text box.

^(?!\.{2,})(?:\d+)?(?:\.{0,1})?(?:\d+)?$

Any suggestions as to what I should try next?

Upvotes: 0

Views: 934

Answers (1)

Eugene Leshchenko
Eugene Leshchenko

Reputation: 11

Example which I propose below, allows to user input all positive numbers in WPF App.

  • if the first char will be ., it will automatically changed to 0. if the first char will be 0, and the second will be the other number, it automatically add point between.

in XAML :

<TextBox Width="100" x:Name="tb" TextChanged="Tb_OnTextChanged" FontSize="20" Margin="15,15,15,15"/>

in code:

private void Tb_OnTextChanged(object sender, TextChangedEventArgs e) {
      var tbx = e.OriginalSource as TextBox;
      string dd = tbx ? .Text;
      if (tbx == null || string.IsNullOrEmpty(dd)) return;
      var tt = dd.Select(r = > r.ToString()).ToList();
      var myregex = ".1234567890".Select(r = > r.ToString()).ToList();
      var ss = new List < string > ();
      tt.ForEach(o = > {
          if (ss.Contains(".") && o != "." || !ss.Contains(".")) {
              if (myregex.Contains(o))
                  ss.Add(o);
              if (ss.FirstOrDefault() == ".") {
                  ss[0] = "0";
                  ss.Add(".");
              }
              if (ss.Count == 2 && ss.FirstOrDefault() == "0" && o != ".") {
                  ss[1] = ".";
                  ss.Add(o);
              }
          }
      });
      var sbc = new StringBuilder();
      ss.ForEach(u = > sbc.Append(u));
      tb.Text = sbc.ToString();
      tb.CaretIndex = tb.Text.Length;
}

Upvotes: 1

Related Questions