简体   繁体   English

如何仅使用正则表达式来限制文本框的文本长度为9位数字

[英]How can I limit my textbox text length takes 9 digits only using regex

  • string pattern = @"^[0-9]{0,9}$"; 字符串模式= @“ ^ [0-9] {0,9} $”;
  • return Regex.IsMatch(input,regFormat); 返回Regex.IsMatch(input,regFormat);
  • I am using above pattern on keydown event Please help me how can I validate my textbox.textlength to max 9 digits using regex and takes only digits not string. 我在keydown事件上使用上述模式,请帮助我如何使用正则表达式将我的textbox.textlength验证为最多9位数字,并且只接受数字而不是字符串。

如果要将正则表达式限制为9个字符,则可以使用大括号,即

/^[0-9]{0,9}$/

To make a TextBox take only 9 characters, you can specify it's MaxLength attribute: 要使TextBox仅包含9个字符,可以指定其MaxLength属性:

myTextBox.MaxLength = 9;

Then, if you only want the user to be able to enter numbers, handle the TextChanged event: 然后,如果只希望用户能够输入数字,请处理TextChanged事件:

myTextBox_TextChanged(object sender, EventArgs e)
{
    if (Regex.IsMatch("[^0-9]",myTextBox.Text)
        myTextBox.Text.Remove(myTextBox.Length - 1);
}

This checks if the last character of the TextBox is not a number, and if it is not a number, removes it. 这将检查TextBox的最后一个字符是否不是数字,如果不是数字,则将其删除。

without regex I found my way out from this problem. 没有正则表达式,我找到了摆脱这个问题的出路。 below codes work awesome on my keydown event 下面的代码在我的keydown事件上很棒

else if (!(e.KeyValue >= 48 && e.KeyValue <= 57) || textBox1.Text.Length == 9)
{
   e.SuppressKeyPress = !(e.KeyCode == Keys.Back || e.KeyCode == Keys.Left || e.KeyCode == Keys.Right);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM