【问题标题】:How to Only allow numbers and a Minus "-" in a Textbox如何在文本框中只允许数字和减号“-”
【发布时间】:2020-03-26 02:59:29
【问题描述】:

我想知道如何才能在文本框中只允许 数字"-" 减号?

这是我已经可以只允许数字的编码:

private void txtDicountSettlement_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    Regex regex = new Regex("[^0-9]+");
    e.Handled = regex.IsMatch(e.Text);
}

【问题讨论】:

  • 那么您是指像 1234 或 -1234 这样的正整数还是负整数,还是像 800-555-5555 这样带有“-”符号的整数?

标签: c# wpf


【解决方案1】:

只需将- 添加到您的正则表达式字符组中,该位置不包含字符范围:

private void txtDicountSettlement_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    Regex regex = new Regex("[^0-9-]+");
    e.Handled = regex.IsMatch(e.Text);
}

【讨论】:

  • @loli 我认为这个函数是逐个字符运行的,它的目的是阻止字符进入文本框,所以是的 - 它会。您需要在其他地方进行不同的验证来处理框中的整个实际值,具体取决于实际可接受的值。这可能是 OP 的下一个问题,但实际上并没有在 Q 中指定。
  • 我不认为 PreviewTextInput 在每个字符之后都被调用。关于这个事件的文档不是很清楚。
【解决方案2】:

我想你想要这样的东西

^[0-9-]*$

它会在任何时候匹配任何数字并且没有破折号并且会忽略任何其他字符

【讨论】:

    【解决方案3】:

    [^-]+[^0-9]+ 应该阻止任何不是整数或负整数的输入。

    【讨论】:

    • 我认为不正确,因为如果值为 50,按减号将变为 -50,但如果再次按减号,它将变为 -50-----
    【解决方案4】:

    添加预览文本输入事件。像这样:<TextBox PreviewTextInput="PreviewTextInput" />

    如果文本不允许,则在其中设置 e.Handled。

    e.Handled = !IsTextAllowed(e.Text);
    

    我在 IsTextAllowed 中使用了一个简单的正则表达式来查看我是否应该允许他们输入的内容。就我而言,我只想允许数字、点和破折号。

    private static bool IsTextAllowed(string text)
    {
        Regex regex = new Regex("[^0-9.-]+"); //regex that matches disallowed text
        return !regex.IsMatch(text);
    }
    

    如果您想防止粘贴不正确的数据,请连接 DataObject.Pasting 事件 DataObject.Pasting="TextBoxPasting",如下所示(代码摘录):

    // Use the DataObject.Pasting Handler 
    private void TextBoxPasting(object sender, DataObjectPastingEventArgs e)
    {
        if (e.DataObject.GetDataPresent(typeof(String)))
        {
            String text = (String)e.DataObject.GetData(typeof(String));
            if (!IsTextAllowed(text))
            {
                e.CancelCommand();
            }
        }
        else
        {
            e.CancelCommand();
        }
    }
    

    【讨论】:

    • 感谢您的评论! :D 这是否能够禁止假设用户输入以下内容:101-101-101-
    • 那么特殊字符呢。如果有人会输入 123213#234% 那会怎样?
    • 是的,它会阻止所有其他不符合条件的字符,在我的情况下只需要“.(dot)”“-(hyphen)”
    • @CareTaker 在您的情况下,您只需从正则表达式中删除 Dot(.) regex = new Regex("[^0-9-]+");
    【解决方案5】:
    private void textBox1_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
    
            if (!char.IsDigit(e.Text, e.Text.Length - 1))
            {
                if(e.Text.Length != 0 || (e.Text.Length == 0 && e.Substring(e.Text.Length - 1) != "-"))
                    e.Handled = true;
    
            }
        }
    

    【讨论】:

      【解决方案6】:

      这是数字文本框的最佳解决方案 这是Answer的回答!

          private bool IsOKForDecimalTextBox(char theCharacter, TextBox theTextBox)
      {
          // Only allow control characters, digits, plus and minus signs.
          // Only allow ONE plus sign.
          // Only allow ONE minus sign.
          // Only allow the plus or minus sign as the FIRST character.
          // Only allow ONE decimal point.
          // Do NOT allow decimal point or digits BEFORE any plus or minus sign.
      
          if (
              !char.IsControl(theCharacter)
              && !char.IsDigit(theCharacter)
              && (theCharacter != '.')
              && (theCharacter != '-')
              && (theCharacter != '+')
          )
          {
              // Then it is NOT a character we want allowed in the text box.
              return false;
          }
      
      
      
          // Only allow one decimal point.
          if (theCharacter == '.'
              && theTextBox.Text.IndexOf('.') > -1)
          {
              // Then there is already a decimal point in the text box.
              return false;
          }
      
          // Only allow one minus sign.
          if (theCharacter == '-'
              && theTextBox.Text.IndexOf('-') > -1)
          {
              // Then there is already a minus sign in the text box.
              return false;
          }
      
          // Only allow one plus sign.
          if (theCharacter == '+'
              && theTextBox.Text.IndexOf('+') > -1)
          {
              // Then there is already a plus sign in the text box.
              return false;
          }
      
          // Only allow one plus sign OR minus sign, but not both.
          if (
              (
                  (theCharacter == '-')
                  || (theCharacter == '+')
              )
              && 
              (
                  (theTextBox.Text.IndexOf('-') > -1)
                  ||
                  (theTextBox.Text.IndexOf('+') > -1)
              )
              )
          {
              // Then the user is trying to enter a plus or minus sign and
              // there is ALREADY a plus or minus sign in the text box.
              return false;
          }
      
          // Only allow a minus or plus sign at the first character position.
          if (
              (
                  (theCharacter == '-')
                  || (theCharacter == '+')
              )
              && theTextBox.SelectionStart != 0
              )
          {
              // Then the user is trying to enter a minus or plus sign at some position 
              // OTHER than the first character position in the text box.
              return false;
          }
      
          // Only allow digits and decimal point AFTER any existing plus or minus sign
          if  (
                  (
                      // Is digit or decimal point
                      char.IsDigit(theCharacter)
                      ||
                      (theCharacter == '.')
                  )
                  &&
                  (
                      // A plus or minus sign EXISTS
                      (theTextBox.Text.IndexOf('-') > -1)
                      ||
                      (theTextBox.Text.IndexOf('+') > -1)
                  )
                  &&
                      // Attempting to put the character at the beginning of the field.
                      theTextBox.SelectionStart == 0
              )
          {
              // Then the user is trying to enter a digit or decimal point in front of a minus or plus sign.
              return false;
          }
      
          // Otherwise the character is perfectly fine for a decimal value and the character
          // may indeed be placed at the current insertion position.
          return true;
      }
      

      然后像As一样在按键事件中调用这个函数

      public void Allow_Only_Numeric(object sender, KeyPressEventArgs e)
          {
              try
              {
      
                  TextBox textbox = (TextBox)sender;
                  Console.WriteLine(textbox.Text);
                  if(IsOKForDecimalTextBox(e.KeyChar,textbox) == true)
                  {
                      e.Handled = false;
                  }
                  else
                  {
                      e.Handled = true;
                  }
              }
              catch (Exception ex)
              {
                  MessageBox.Show(ex.Message);
      
              }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-24
        相关资源
        最近更新 更多