简体   繁体   中英

Regex to allow only numbers between 100 and 999999

Can anyone help with C# code using regular expressions to validate a textbox which accepts only numbers between 100 and 999999

Thanks, Lui.

You don't need a regex for this.

int n;
if (!int.TryParse(textBox.Text.Trim(), out n) || n<100 || n>999999)
{
  // Display error message: Out of range or not a number
}

EDIT: If the CF is targetted, then you can't use int.TryParse() . Fallback on int.Parse() instead and type a little more error-catching code:

int n;
try
{
  int n = int.Parse(textBox.Text.Trim());
  if (n<100 || n>999999)
  {
    // Display error message: Out of range
  }
  else
  {
    // OK
  }
}
catch(Exception ex)
{
   // Display error message: Not a number. 
   //   You may want to catch the individual exception types 
   //   for more info about the error
}

Your requirement translates to three to six digits, first not zero. I can't remember whether C# anchors REs by default, so I've put them in too.

^[1-9][0-9]{2,5}$

A straightforward approach would be to use the regex

^[1-9][0-9]{2,5}$

If you want to allow leading zeroes (but still keep the 6-digit limit) the regex would be

^(?=[0-9]{3,6}$)0*[1-9][0-9]{2,5}

This last one probably merits some explanation: it first uses positive lookahead [ (?=) ] to make sure that the whole input is 3 to 6 digits, and then it makes sure that it's made up of any number of leading zeroes followed by a number in the range 100-999999.

However , it's possibly a good idea to use something more suited to the task (maybe a numeric comparison?).

Do you have to use regex? How about

int result;
if(Int.TryParse(string, out result) && result > 100 && result < 999999) {
    //do whatever with result
}
else
{
    //invalid input
}

这将达到目的:

^[1-9]\d{2,5}$

您可以考虑的另一种方法

[1-9]\\d{2,5}

Why not use a NumericUpDown control instead which lets you specifiy a Minimum and Maximum value? And it will only allow numbers too, saving you additional validation to ensure anything non-numeric can be entered

From the example:

public void InstantiateMyNumericUpDown()
{
   // Create and initialize a NumericUpDown control.
   numericUpDown1 = new NumericUpDown();

   // Dock the control to the top of the form.
   numericUpDown1.Dock = System.Windows.Forms.DockStyle.Top;

   // Set the Minimum, Maximum, and initial Value.
   numericUpDown1.Value = 100;
   numericUpDown1.Maximum = 999999;
   numericUpDown1.Minimum = 100;

   // Add the NumericUpDown to the Form.
   Controls.Add(numericUpDown1);
}

也许接受前导零:

^0*[1-9]\d{2,5}$

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