简体   繁体   中英

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

  • string pattern = @"^[0-9]{0,9}$";
  • return 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.

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

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

To make a TextBox take only 9 characters, you can specify it's MaxLength attribute:

myTextBox.MaxLength = 9;

Then, if you only want the user to be able to enter numbers, handle the TextChanged event:

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.

without regex I found my way out from this problem. below codes work awesome on my keydown event

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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