【问题标题】:Validating a textbox to allow only numeric values [duplicate]验证文本框以仅允许数值[重复]
【发布时间】:2012-10-26 12:48:38
【问题描述】:

可能重复:
How do I make a textbox that only accepts numbers?

我有一个电话号码,我希望将其存储为字符串。

我在使用

时读到了这篇文章
txtHomePhone.Text

我认为我需要的是某种数字,但无法使其正常工作

if (txtHomePhone.Text == //something.IsNumeric)
{
    //Display error
}
else
{
    //Carry on with the rest of program ie. Add Phone number to program.
}

只允许输入数值的最佳方法是什么?

【问题讨论】:

  • txtHomePhone 是否代表TextBox?如果是这样,您可以使用KeyPress 事件来接受您希望允许的字符并拒绝您不希望在TextBox 中输入的字符。祝你有美好的一天:)
  • 它确实代表一个文本框,我如何找出哪个按键是哪个?
  • 这是一个 Web 还是客户端应用程序?
  • Springfox,查看@TyrionLannister 提供的链接 - 第一个答案有一些代码向您展示如何处理按键事件并且只让数字通过。如果您希望将 IF 功能保持在上面,请查看下面 davenewza 的答案(TryParse)。例如,您还可以使用 Regex 匹配更复杂的字符串并检测字符串是否使用“(xxx) xxx-xxxx”格式。

标签: c# validation


【解决方案1】:

试试这个

if (!txtHomePhone.Text.All(c=> Char.IsNumber(c)))
{
    //Display error
}
else
{
    //Carry on with the rest of program ie. Add Phone number to program.
}

【讨论】:

  • 这是做什么的?它为您提供一个真/假值,但不提供任何真正的验证。 (此外,对于原始问题中使用的电话号码示例,它可能还不够:对于可能在典型电话号码输入中的符号和空格,它将返回 false。)
  • @DanPuzey 在他的例子中,他特别写了: if (txtHomePhone.Text == //something.IsNumeric )。所以我认为没有空格等。关于验证,他所要做的就是检查 isNumeric。我将代码添加到 if 语句中以便更好地解释。
【解决方案2】:

要检查是否输入了数值,可以使用Integer.TryParse

int num;
bool isNum = Integer.TryParse(txtHomePhone.Text.Trim(), out num);

if (!isNum)
    //Display error
else
    //Carry on with the rest of program ie. Add Phone number to program.

但请记住,电话号码不一定只是数字。请参阅 Trevor Pilley 答案以获取蒙版文本框。

【讨论】:

    【解决方案3】:

    我假设您在这里使用的是 Windows 窗体,请查看 MaskedTextBox。它允许您指定字符的输入掩码。

    txtHomePhone.Mask = "##### ### ###";
    

    由于这允许您限制输入值,您可以安全地将值解析为整数。

    注意:如果您使用的是 WPF,我认为基础库中没有 MaskedTextBox,但是 NuGet 上提供的扩展可能会提供类似的功能。

    【讨论】:

    • 他正在寻找一种方法来验证数字是否为数字,而不是隐藏其中的内容。
    • 掩码指定允许的字符,它不会像密码输入掩码一样隐藏输入。
    • @TyrionLannister A Maskedtextbox 不会隐藏它强制输入符合“掩码”的值。因此,在 Trevor 的示例中,文本框将仅显示格式为 "##### ### ###" 的 11 个数字。空间被强制在那里。
    • 我很抱歉。时间还早,我看了《面具》。
    • @TyrionLannister - 很容易做到,我们都去过那里:o)
    【解决方案4】:

    通常我会按照 davenewza 的建议使用 Integer.TryParse,但另一种选择是使用 C# 中的 VisualBasic IsNumeric 函数。

    添加对 Microsoft.VisualBasic.dll 文件的引用,然后使用以下代码。

    if (Microsoft.VisualBasic.Information.IsNumeric(txtHomePhone.Text))
    {
        //Display error
    }
    else
    {
        //Carry on with the rest of program ie. Add Phone number to program.
    }
    

    【讨论】:

      【解决方案5】:

      由于txtHomePhone 代表TextBox,您可以使用KeyPress 事件来接受您希望允许的字符并拒绝您不希望在txtHomePhone 中允许的字符

      示例

      public Form1()
      {
          InitializeComponent();
          txtHomePhone.KeyPress += new KeyPressEventHandler(txtHomePhone_KeyPress);
      }
      private void txtHomePhone_KeyPress(object sender, KeyPressEventArgs e)
      {
          if (e.KeyChar >= '0' && e.KeyChar <= '9' || e.KeyChar == '') //The  character represents a backspace
          {
              e.Handled = false; //Do not reject the input
          }
          else
          {
              e.Handled = true; //Reject the input
          }
      }
      

      通知The following character (which is not visible) represents a backspace.
      注意:您始终可以使用e.Handled 来允许或禁止特定字符。
      注意:如果您想使用 -</kbd>、<kbd>@,可以创建条件语句987654330@</kbd> 或 <kbd>) 仅一次。如果您希望在特定位置输入这些字符,我建议您使用正则表达式。

      示例

      if (e.KeyChar >= '0' && e.KeyChar <= '9' || e.KeyChar == '') //The  character represents a backspace
      {
          e.Handled = false; //Do not reject the input
      }
      else
      {
          if (e.KeyChar == ')' && !txtHomePhone.Text.Contains(")"))
          {
              e.Handled = false; //Do not reject the input
          }
          else if (e.KeyChar == '(' && !txtHomePhone.Text.Contains("("))
          {
              e.Handled = false; //Do not reject the input
          }
          else if (e.KeyChar == '-' && !textBox1.Text.Contains("-"))
          {
              e.Handled = false; //Do not reject the input
          }
          else if (e.KeyChar == ' ' && !txtHomePhone.Text.Contains(" "))
          {
              e.Handled = false; //Do not reject the input
          }
          else
          {
              e.Handled = true;
          }
      }
      

      谢谢,
      希望对您有所帮助:)

      【讨论】:

      • 允许 123(例如我在 Visual Basic .net 中尝试过
      • 超级有用的答案,谢谢。我不得不在 Visual C# MVStudio 环境中使用 e.KeyChar=='\b' 来捕获退格键(而不是 e.KeyChar=='')。我使用您的模式来接受特定字符的一个实例,以接受我的数值中的小数点。
      【解决方案6】:

      我发现最好的方法是只允许用户在文本框中输入数字键,感谢您的帮助。

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-25
      • 1970-01-01
      • 2021-06-21
      • 2021-12-28
      • 1970-01-01
      • 2015-09-03
      相关资源
      最近更新 更多