2

I want to validate the text within a textbox using a regular expression.
The text should be a number greater than 0 and less than and equal to 1000.

2
  • You dont want to use range validator?? Commented Aug 1, 2012 at 7:31
  • want to do by regular expression validator only Commented Aug 1, 2012 at 8:04

3 Answers 3

3

"^[1-9][0-9]*{1,2}$" is the regex you are looking for.

if(Regex.IsMatch(YourTextBox.Text,"^[1-9][0-9]*{1,2}$"))
{
    //Write your logic here 
}
Sign up to request clarification or add additional context in comments.

6 Comments

I think less than 1000 means 3 digits max, therefore {1,3} should be {1,2} as you've alreay got the first digit from the [1-9].
This code return ArgumentException was unhandled:parsing "^[1-9][0-9]*{1,2}$" - Nested quantifier {.
a ) is needed at the end of first line
but i want validate expression
same here return argument exception
|
0

Try this regex:

//for  0 < x < 1000
^((?<=[1-9])0|[1-9]){1,3}$

explain:

(?<=[1-9])0     //look behind to see if there is digits (1-9)

test:

0   ->  invalid
000 ->  invalid
45  ->  valid
5   ->  valid      'Ashwin Singh' solution can not capture this
101 ->  valid
999 ->  valid
1000    ->  invalid
12345   ->  invalid
10000   ->  invalid
2558    ->  invalid
205 ->  valid
1001    ->  invalid
2000    ->  invalid

And better way convert to Decimal (if you dont use regular expression validator):

Decimal dc = Decimal.TryParse(textBox.Text);
if( dc > 0 && dc < 1000)
// do some thing

1 Comment

The ((?<=\d)0|[1-9]){1,3} return true for value greater than 1000
0

I found it:

^([1-9]|[1-9][0-9]|[1-9][0-9][0-9])$|^(1000)

I test it in range 0~1000

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.