You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现TextBox仅允许输入数字且首字符不为0?

实现TextBox仅允许输入数字且首字符非0的功能优化

一、优化仅允许输入数字的代码

现有代码仅限制输入数字,要添加首字符不能为0的规则,可修改如下:

private void textbox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    TextBox tb = sender as TextBox;
    // 非数字直接阻止输入
    if (!Char.IsDigit(e.Text, 0))
    {
        e.Handled = true;
        return;
    }
    // 如果输入的是0,且文本框当前为空(即首字符要输入0),阻止输入
    if (e.Text == "0" && string.IsNullOrEmpty(tb.Text))
    {
        e.Handled = true;
    }
}

逻辑说明:

  • 保留原有过滤非数字输入的功能
  • 新增判断:当文本框为空时,不允许输入0作为首字符

二、优化允许输入单个逗号的代码

现有代码支持数字和单个逗号,要添加首字符非0的限制,同时保留逗号的规则(仅一个逗号、不能开头加逗号),修改后代码如下:

private void textbox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    TextBox tb = sender as TextBox;
    // 输入非数字且非逗号,直接阻止
    if (!Char.IsDigit(e.Text, 0) && e.Text != ",")
    {
        e.Handled = true;
        return;
    }

    // 处理逗号规则:已有逗号则阻止,文本框为空时不能输入逗号
    if (e.Text == ",")
    {
        if (tb.Text.Contains(",") || string.IsNullOrEmpty(tb.Text))
        {
            e.Handled = true;
        }
        return;
    }

    // 处理首字符非0规则:输入0且文本框为空时阻止
    if (e.Text == "0" && string.IsNullOrEmpty(tb.Text))
    {
        e.Handled = true;
    }
}

逻辑说明:

  1. 过滤非数字非逗号的输入
  2. 逗号限制:文本框已有逗号或为空时,禁止输入逗号
  3. 首字符限制:文本框为空时,禁止输入0作为开头

内容的提问来源于stack exchange,提问作者Chārry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 21:14:58